Ingro
Ingro

Reputation: 2841

RequireJS: require a module return a function instead of a object

I'm noticing a strange behaviour with RequireJS trying to assign a simple module value directly to a variable, like this:

App.tables = require(['appTables']);

The result of this call is that App.tables contain this function:

localRequire(deps, callback, errback)

while my appTables.js looks like this:

define({
  users: {
    name: 'tables.users',
    data: {
      name: {
        visible: true,
        hide: false,
        display: 'Name'
      },
      surname: {
        visible: true,
        hide: false,
        display: 'Surname'
      }
    }
  }
});

Indeed trying to assign it in the classic way works:

require(['appTables'], function(appTables) {
    App.tables = appTables;
});

So what's wrong with my first approach? Why does it return a function instead of the object? Thanks!

Upvotes: 1

Views: 6149

Answers (1)

Chris Salzberg
Chris Salzberg

Reputation: 27374

The simplified CommonJS format which you're using (App.tables = require('appTables')) is meant to be used within a module, as an alternative to the amd format where you assign an array of module dependencies to function arguments. It is not meant to be used in your main.js module (just use the standard require('appTables', function(appTables) { ... }); format for that).

In a module, you would wrap the require call in a define block, and pass the module name ('appTables'):

define(function(require) {
  appTables = require('appTables');
  ... do something with appTables ...
});

See the documentation on the Simplified CommonJS Wrapper for details.

See also: Why use alternate requirejs define: define(function(require) { ... }

Upvotes: 3

Related Questions