Use require.js to run common code before module is

2019-05-11 00:13发布

问题:

I'm using Moment.js on a few different pages in an international site. Each page uses require.js to require in Moment.

Moment allows you to set the locale to display dates in that locales format. However, this code has to be run on every page Moment is loaded (since I'm never sure which page the user loads first).

var Moment = require('moment');
// configure locale

What I want to do is move the code to configure the locale to something like a pre-require step so that I don't have to remember to configure the locale on every page (and it becomes more DRY). So all I would have to do is

var Moment = require('moment');

and the pre-require step would already have configured the locale.

Is this possible?

回答1:

Yes, it is possible, like this:

  1. Create a module that will be called moment-configured:

    define(['moment'], function (moment) {
        // Call what you need to call to configure moment...
        return moment;
    });
    
  2. Use a map configuration so that everybody who loads moment really loads your moment-configured module whereas moment-configured loads the real moment:

    map: {
        '*': {
            moment: 'moment-configured'
        },
        'moment-configured': {
             moment: 'moment'
        }
    }
    

This method is adapted from the example in RequireJS' documentation about how to have jQuery be automatically loaded with noConflict. With this map configuration, all modules that require moment will get moment-configured, except for moment-configured which will get the real moment.



回答2:

The require config object can be given a callback to be executed after dependencies are loaded and before require() is defined:

requirejs.config({
    deps: ['moment'],
    callback: function (moment) {
        console.log(moment().format());
    }
});