使用gruntjs将所有凉亭库合并并缩小

时间:2014-08-15 06:49:30

标签: gruntjs minify bower grunt-contrib-uglify wiredep

有没有办法将所有bower安装的库自动组合并缩小为1个文件?

首先,我尝试了最基本的方法:合并所有子目录中的所有.js个文件:

uglify: {
    options: {compress: true},
    my_target: { files: {
        'vendor.js': ['bower_components/**/*.js'],
}   }   }

但这显然是一种糟糕的做法。由于错误太多,它也不起作用。

我手动删除了所有文件,并且只保留了每个库所拥有的1个(主)文件,并且它有效。

有没有办法自动完成这项工作?

另外,建议这样做吗? (即将所有供应商库合并为1个文件)

2 个答案:

答案 0 :(得分:12)

我推荐2个不错的grunt库,Wiredep和Usemin:

的组合

Wiredep:自动加载html中bower.json中识别的bower的所有依赖关系

Usemin:检测两个注释标记内的所有src,并且所有源都在dist文件夹中缩小和连接,下面是使用此包的grunt文件的一个小例子,是基于angular to yeoman的生成器这只是一个那个咕噜的简要说明

<强>咕噜

    wiredep: {
        options: {
            cwd: 'appFolder'
        },
        app: {
            src: ['htmlCollections'],
            ignorePath:  /\.\.\//
        }
    },

    useminPrepare: {
        html: 'htmlCollections',
        options: {
            dest: 'distributionFolder',
            flow: {
                html: {
                    steps: {
                        js: ['concat', 'uglifyjs'],
                        css: ['cssmin']
                    },
                    post: {}
                }
            }
        }
    },

  usemin: {
        html: ['distributionFolder+HtmlFiles'],
        css: ['distributionFolder+cssFiles'],
        js: ['distributionFolder+javascriptFiles']
  }

<强> HTML

<!doctype html>
<html lang="en" ng-app="MobileDev" id="ng-app">
<head>
    <!-- build:css(app) styles/vendor.css -->
    <!-- bower:css -->
            //This gonna be generated for the grunt by dependencies in bower
    <!-- endbower -->
    <!-- endbuild -->

    <!-- build:css(.tmp) styles/main.css -->
        //All the script inside this gonna be concatened and minified in 
        //the dist folder by the name of main.css
        <link type="text/css" rel="stylesheet" href="styles/app.css"/>
    <!-- endbuild -->
</head>

<body>
    <!-- build:js(app) scripts/vendor.js -->
    <!-- bower:js -->
        //This gonna be generated for the grunt by dependencies in bower
        //And in distribution all bower components added gonna be minified by usemin in
        //vendor.js
    <!-- endbower -->
    <!-- endbuild -->

    <!-- build:js({.tmp,app}) scripts/scripts.js -->
        //All the script inside this gonna be concatened and minified in the dist 
        //folder by the name of scripts.js
        <script type="text/javascript" src="scripts/numero1"></script>
        <script type="text/javascript" src="scripts/numero2"></script>
    <!-- endbuild -->

</body>

答案 1 :(得分:5)

只需要wiredep

uglify: {
    options: { compress: true },
    my_target: { 
        files: { 'public/vendor.js': require('wiredep')().js
}   }   },
cssmin: {
    minify: {
        files: { 'public/vendor.css': require('wiredep')().css
}   }   },