合并/压缩js文件
You can either specify options on the command line:
node r.js -o baseUrl=. paths.jquery=some/other/jquery name=main out=main-built.js
or in a build profile. In a
build.js
, the same command line arguments can be specified like so:
({
baseUrl: ".",
paths: {
jquery: "some/other/jquery"
},
name: "main",
out: "main-built.js"
})
then just pass the build profile's file name to the optimizer:
node r.js -o build.js
optimize (none/uglify/closure) 指定是否压缩,默认为uglify
不传该参数时r.js默认以UglifyJS压缩。设置为none则不会压缩,仅合并
baseUrl, it is relative to appDir. If no appDir, then baseUrl is relative to the build.js file
For paths and packages, they are relative to baseUrl
The mainConfigFile option can be used to specify the location of the runtime config. If specified with the path to yourmain JS file, the first
requirejs({}), requirejs.config({}), require({}), or require.config({}) found in that file will be parsed out and used as part of the
configuration options passed to the optimizer
压缩整个项目
//app.build.js
({
appDir: "../", //以本文件为起点,配置项目根目录
baseUrl: "scripts",
dir: "../../appdirectory-build", //为了不影响源码,输出到同级目录
mainConfigFile: "main.js" //入口配置文件的位置
})
node ../../r.js -o app.build.js 压缩遇到问题:
特别需要注意的是Angular应用压缩问题。否则错误信息比如 ‘Unknown provider:aProvider <- a’ 会让你摸不到头脑。跟其他很多东西一样,这个错误在官方文档里也是无从查起的。简而言之,Angular依赖参数名来进行依赖注入。压缩器压根意识不到这个这跟Angular里普通的参数名有啥不同,尽可能的把脚本变短是他们职责。咋办?用“友好压缩法”来进行方法注入。看这里:
module.service('myservice',function($http, $q) {
// This breaks when minified
});
to this:
module.service('myservice', [ '$http','$q',function($http, $q) {
// Using the array syntax to declare dependencies works with minification!
}]);
这个数组语法很好的解决了这个问题。我的建议是从现在开始照这个方法写,如果你决定压缩JavaScript,这个方法可以让你少走很多弯路
最终一点建议:如果你想用数组语法复写你的functions,在所有Angular依赖注入的地方应用之。包括directives,还有directive里的controllers。别忘了逗号(经验之谈)
// the directive itself needs array injection syntax:
module.directive('directive-with-controller', ['myservice',function(myservice) {
return{
controller: ['$timeout',function($timeout) {
// but this controller needs array injection syntax, too!
}],
link : function(scope, element, attrs, ctrl) {}
}
}]);
311

被折叠的 条评论
为什么被折叠?



