RequireJS: loading different files according environment

ⅰ亾dé卋堺 提交于 2019-11-30 21:15:25

If you use the r.js optimizer then this process can be taken care of for you. In your scripts folder leave all modules, libs and other code uncompressed for dev purposes. I often have something like this

scripts/
    lib/
    modules/

When ready to deploy, create a build.js and configure the various options. I'll give an example of a similar config I have used:

({
    baseUrl: '../scripts',
    dir: '../scripts.min',

    paths: {
        'jquery': 'lib/jquery'
    },

    removeCombined: true,

    optimize: 'uglify',
    preserveLicenseComments: false,
    uglify: {
        max_line_length: 3500,
        no_copyright: true
    },

    modules: [
        {
            name: 'module1'
        },
        {
            name: 'module2',
            exclude: ['jquery']
        }
    ]
})

More details on each of this options can be found in this example configuration but I will draw attention to dir and removeCombined

dir is obviously where your scripts will end up. I tend to create a folder adjacent to my scripts with the suffix .min or something similar. Then, when you're ready to go to production, simply change your require config baseUrl to scripts.min

require.config({
    baseUrl: '/scripts.min' // Now the site will load scripts from the optimised folder

    // Other options
})

By default, r.js will copy all the scripts over regardless of whether they have already been combined into another js file or not. Setting the removeCombined to true will ensure your scripts.min folder only has the necessary files for production.

If someone still want to know how to do that:

require.config({
    paths: {
        'jquery' : (function(){
            if( MODE == 'DEV' ){
                return 'jquery';
            }else{
                return 'jquery.min'
            }
        })()
    }
});

This function is self invoking anonymous function. It invokes immediately in the definition place.

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