How to optimize a project using requireJS if we defined some maps in config?

I have require.config in my main as below.

require.config ({
BaseUrl: 'scripts /',

paths:{ jquery:'shell/lib/jquery/jquery-1.7.1' // many libraries and modules are aliased here }, map:{ '*':{ 'underscore':'shell/lib/underscore/underscore' // a few other modules are mapped here } } 

});

I did this because the files defined on the map use internal dependencies (in their respective folders) using relative paths. Now when I run the optimizer, the modules defined in the path are saved as module identifiers, such as jquery, saved as jquery , and those on the map get full paths, such as "underscore" like "shell / lib / underscore / underline 'instead of' underline '.

This causes problems, since I use "underscore" in other modules, and there the optimized file has "underscore" instead of "shell / lib / underscore / underscore".

Is there any specific way to optimize when we give configuration cards or something that I am missing? Please tell me how to fix it.

thanks

+4
source share
1 answer

I am not sure to understand the problem:

This causes problems, since I use "underscore" in other modules, and there the optimized file has "underscore" instead of "shell / lib / underscore / underscore".

This is apparently the expected behavior; you have mapped the underscore to this path for all modules. So basically you specify r.js : every time you find that the underscore dependency overwrites it to shell/lib/underscore/underscore . If your modules use "internal paths" and you want to do the opposite (link to underscore ), you need to do the opposite mapping:

  'some/path/underscore': 'underscore' 

In this case, all modules will point to the same underline module. Even those that use some weird way to underline.

As a last resort, you need to control how r.js writes modules to disk. You can use the onBuildWrite property (see https://github.com/jrburke/r.js/blob/master/build/example.build.js#L517 ).

For instance:

 onBuildWrite: function ( moduleName, path, contents ) { if ( path === './src/somefile.js' ) { return contents.replace(/^define\('src\/underscore'/, "define('underscore'"); } else { return contents; } } 

This example is a โ€œhackโ€ that r.js tells: when processing somefile.js replace src/underscore with underscore (this is exactly what you do with the map), but just to show you how you can use onBuildWrite to do nasty things).

+1
source

Source: https://habr.com/ru/post/1435417/


All Articles