使用RequireJS模塊化后代碼被拆分成多個JS文件了,在部署生產環境需要壓縮合並,RequireJS提供了一個打包壓縮工具r.js來對模塊進行合並壓縮。r.js非常強大,不但可以壓縮js,css,甚至可以對整個項目進行打包。
r.js的壓縮工具使用UglifyJS或Closure Compiler。默認使用UglifyJS(jQuery也是使用它壓縮)。此外r.js需要node.js環境,當然它也可以運行在Java環境中如Rhino。JAVA環境使用Ant構建可以參考另外一篇RequireJS optimizer Ant task有介紹。node環境參考RequireJS模塊化與GruntJS構建。
本篇介紹require.js官方文檔中介紹的方法。
build.xml
{
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 就可以壓縮合並模塊。
項目參考https://github.com/requirejs/example-multipage/blob/master/tools/build.js
