what is the difference between require and require

486 Views Asked by At

What is the difference between these two with and without almond?

require('module'); require(['module']);

Edit

which are nested:

define(function() { require('module'); }

define(function() { require(['module']); }

former gives a requirejs error (that suggests to use the ladder).

The reason i am asking is,

I am studying example-libglobal on how to build a lib that can be used as an AMD module.

The library module we want to export:

File: principium.js

/**
* The main module that defines the public interface for principium,
*/
define(function (require) {
    convert = require('principium/convert');

    //Return the module value.
    return {
        convert: convert
    };
});

The main module that returns the library module.

File: lib/main.js

define(function() {
    //Use almond's special top-level, synchronous require to
    //get the final module value, and export it as the public
    //value.
    return require('principium');
});

In this example it uses almond to require principium (return require('principium')), i expect that to return the exported library object.

But i don't use almond, and require('principium') syntax gives error, and if i use require(['principium']) instead, that doesn't return the exported library object.

exported library object, That is i mean return { convert: convert }; returned in principium.js.

Edit

How can i use nested require properly so that:

var moduleExport = require('module');

works as i expect.

Edit

I solved it, but i don't know how it worked, I included almond in the build and it worked magically.

"include": ["../bower_components/almond/almond", "lib/main"]

and refactored

File: lib/main.js

define([], function() {
    return require('principium');
});
1

There are 1 best solutions below

7
On

It's "latter", because it's the later clause of two options, not ladder, which is a thing you climb up or down to reach otherwise impossible to reach elevations.

With that bit of "the more you know" out of the way: if you're using require.js, you cannot just require a module: require.js is for loading dependencies, in order to run a function, so the syntax is:

require(
  ['dependency1', 'dependency1',...],
  function codetorun(dep1, dep2) { ... }
);

your function is dependent on code from dependency1, etc, and therefore you "require" that code to be loaded and made available as variables to your function, before the function should even run.

Simply requiring in a module, without needing it for something, makes no sense as far as require.js can tell, so it throws an error.