您的位置:首页 > Web前端 > JavaScript

Gruntjs: grunt-usemin使用心得

2014-03-10 00:00 573 查看
grunt-usemin


Replaces references to non-optimized scripts or stylesheets into a set of HTML files


usemin
exports 2 different tasks:

useminPrepare
prepares the configuration to transform specific construction (blocks) in the scrutinized file into a single line, targeting an optimized version of the files

usemin
replaces the blocks by the file they reference, and replaces all references to assets by their revisioned version if it is found on the disk. This target modifies the files it is working on.

Usually,
useminPrepare
is launched first, then the steps of the transformation flow (for example,
concat
,
uglify
, and
cssmin
), and then, in the end
usemin
is launched.

我的工作目录

workspace/

  ——app/

    ——js/

    ——tpl/

Gruntfile.js配置

module.exports = function(grunt) {

// Project configuration.
grunt.initConfig({

useminPrepare: {
html: ['app/tpl/**/*.html'],
options: {
// 测试发现这里指定的dest,是usemin引入资源的相对路径的开始
// 在usemin中设置assetsDirs,不是指定的相对路径
// List of directories where we should start to look for revved version of the assets referenced in the currently looked at file
dest: 'build/tpl'               // string type
}
},
usemin: {
html: ['build/tpl/**/*.html'],      // 注意此处是build/
options: {
assetsDirs: ['build/js']
}
},
copy: {
html: {
expand: true,                   // 需要该参数
cwd: 'app/',
src: ['tpl/**/*.html'],         // 会把tpl文件夹+文件复制过去
dest: 'build'
}
}

});

grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-usemin');

// 最后就是顺序了,没错concat,uglify在这里哦!
grunt.registerTask('default', [
'copy:html',
'useminPrepare',
'concat:generated',
'uglify:generated',
'usemin'
]);

};


源html结构

<body>
<p>this is a grunt usemin</p>

<script src="../js/globle.js"></script>

<!-- build:js ../js/page.js -->
<script src="../js/libs.js"></script>
<script src="../js/page.js"></script>
<!-- endbuild -->
</body>


打包后的html

<body>
<p>this is a grunt usemin</p>

<script src="../js/globle.js"></script>

<script src="../js/page.js"></script>
</body>


感谢gruntjs,yeoman
https://github.com/yeoman/grunt-usemin
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: