Use require.js to run common code before module is required

左心房为你撑大大i 提交于 2020-01-02 06:58:29

问题


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());
    }
});


来源:https://stackoverflow.com/questions/26807294/use-require-js-to-run-common-code-before-module-is-required

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!