RequireJS模塊化後JS壓縮合並

使用RequireJS模塊化後代碼被拆分紅多個JS文件了,在部署生產環境須要壓縮合並,RequireJS提供了一個打包壓縮工具r.js來對模塊進行合併壓縮。r.js很是強大,不但能夠壓縮js,css,甚至能夠對整個項目進行打包。css

r.js的壓縮工具使用UglifyJSClosure Compiler。默認使用UglifyJS(jQuery也是使用它壓縮)。此外r.js須要node.js環境,固然它也能夠運行在Java環境中如Rhino。JAVA環境使用Ant構建能夠參考另一篇RequireJS optimizer Ant task有介紹。node環境參考RequireJS模塊化與GruntJS構建html

本篇介紹require.js官方文檔中介紹的方法。node

build.xmljquery

{
    appDir: '../www',
    baseUrl: 'js/lib',
    paths: {
        app: '../app'
    },
    dir: '../www-built',
    modules: [
        //First set up the common build layer.
        {
            //module names are relative to baseUrl
            name: '../common',
            //List common dependencies here. Only need to list
            //top level dependencies, "include" will find
            //nested dependencies.
            include: ['jquery',
                      'app/lib',
                      'app/controller/Base',
                      'app/model/Base'
            ]
        },
 
        //Now set up a build layer for each page, but exclude
        //the common one. "exclude" will exclude nested
        //the nested, built dependencies from "common". Any
        //"exclude" that includes built modules should be
        //listed before the build layer that wants to exclude it.
        //"include" the appropriate "app/main*" module since by default
        //it will not get added to the build since it is loaded by a nested
        //require in the page*.js files.
        {
            //module names are relative to baseUrl/paths config
            name: '../page1',
            include: ['app/main1'],
            exclude: ['../common']
        },
 
        {
            //module names are relative to baseUrl
            name: '../page2',
            include: ['app/main2'],
            exclude: ['../common']
        }
 
    ]
}

在node環境下執行 node r.js -o build.js 就能夠壓縮合並模塊。git

項目參考https://github.com/requirejs/example-multipage/blob/master/tools/build.jsgithub

相關文章
相關標籤/搜索