Using config in a RequireJS plugin

2019-07-20 20:01发布

问题:

I'm trying to write a RequireJS plugin that takes in the name of the module requested, dynamically figures out its path, then loads it. The logic to determine these paths is based on some specific business logic, so it's unlikely any existing plugins that do similar things will be useful to me.

I initially tried to use the plugin's normalize method, but weird things were happening: normalize was being called twice, after which the load method was called with an empty string for the name.

I got everything working perfectly without normalize, using the config parameter of load. Is this a suitable solution without any hidden side effects?

define('module-loader', {
    load: function(name, req, onload, config){
        var nameParts = name.split('-'),
                langFile = nameParts.length === 3 && nameParts[2] === 'langs',
                indFiles = CR_DEBUG;

        if (nameParts.length > 3){
            //allow for helper names with a dash in them
            nameParts[2] = nameParts.slice(2).join('-');
        }
        var resolvedName = resolve.apply(null, nameParts);

        config.paths[name] = resolvedName;
        req([name], function (value) {
            onload(value);
        });
    }
});

I would assume the config object is simply the current requireJS config object, which can be added to. And the results I'm seeing do indeed imply that this is the case. But the doc's have a rather different explanation for what the config object does:

config: Object. A configuration object. This is a way for the optimizer and the web app to pass configuration information to the plugin. The i18n! plugin uses this to get the current current locale, if the web app wants to force a specific locale. The optimizer will set an isBuild property in the config to true if this plugin (or pluginBuilder) is being called as part of an optimizer build.

Parts of that explanation do imply what I suggested, but I'm hoping an expert can answer more certainly.


For what it's worth, this is what I had for my normalize method. I'm perfectly happy with the solution I currently have, but if there's something obviously wrong with what's below, I'd love to hear what:

normalize: function (name) {
    //weird - normalize getting called twice - hack fix for now
    if (/^\//.test(name)) return name;

    var nameParts = name.split('-'),
        langFile = nameParts.length === 3 && nameParts[2] === 'langs',
        indFiles = CR_DEBUG;

    if (nameParts.length > 3){
        //allow for helper names with a dash in them
        nameParts[2] = nameParts.slice(2).join('-');
    }
    var resolvedName = resolve.apply(null, nameParts)

    //alert('returning:' + resolvedName);
    return resolvedName;
},

//and after this there was just a regular load method loaded 
//the name it was passed, but name was coming in as ""