requirejs优化:使用r.js压缩文件

合并/压缩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则不会压缩,仅合并


configuration options:

 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"  //入口配置文件的位置

})
运行命令(因为r.js在整个项目之外,app.build.js位于/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) {}
    }
}]);



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值