3

In Magento 2, there's a mageUtils RequireJS module alias that points to mage/utils/main. If you look at the source of this module

#File: vendor/magento/magento2-base/lib/web/mage/utils/main.js

define(function (require) {
    'use strict';

    var utils = {},
        _ = require('underscore');

    return _.extend(
        utils,
        require('./arrays'),
        require('./compare'),
        require('./misc'),
        require('./objects'),
        require('./strings'),
        require('./template')
    );
});

You can see this code directly calls require to pull in dependencies rather than listing them as define dependencies. I'd expect to see something more like this

define(['./arrays',
        './compare',
        './misc',
        './objects',
        './strings',
        './template'], function (Arrays, Compare, Misc, Objects, Strings, Template) {
    'use strict';

    var utils = {},
        _ = require('underscore');

    return _.extend(
        utils, Arrays, Compare, Misc, Objects, Strings, Template
    );
});

It's my understanding that directly calling require or requirejs to fetch a module reference only works if the module's already been loaded. Therefore, this means the mage/utils/main module can only be used if it's loaded in a particular order as part of the Magento bootstrap process.

  1. Is this an incorrect assumption about directly calling require?
  2. Is there a technical reason the mage/utils/main utility doesn't use define dependencies to pull these modules in?
2

This is "simplified CommonJS wrapping". A special form of RequireJS module declaration. In this case require calls are parsed by RequireJs and executed before this function is executed.

Some links:

We discourage it in new code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.