前端优化是尽量减少http请求,所以我们需要尽量合并压缩文件,然后调用压缩后的文件,比如多个css文件压缩成一个,多个js文件合并压缩等,usemin能够自动在html中使用压缩后的文件,达到上面的目的。
上图是完整打包后的文件目录,原始目录是assets,打包发布的文件是dist.
gruntfile.js文件内容:
module.exports = function(grunt) { grunt.config.init({
clean:{
src:"dist/"
},
useminPrepare: {
html: 'index.html',
options: {
dest: 'dist'
}
},
usemin: {
html: ['dist/index.html']
},
uglify: {
'dist/js/app.min.js': ['assets/js/*.js']
},
copy: {
html: {
src: './index.html',
dest: 'dist/index.html'
}
},
cssmin:{
'dist/css/app.min.css': ['assets/css/*.css']
}
});
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-usemin');
grunt.registerTask('default',[
'clean',
'copy:html',
'useminPrepare',
'uglify',
'cssmin',
'usemin'
]);
}
原始的index.html
<!DOCTYPE html>
<html>
<head>
<title>Usemin test</title>
<!-- build:css dist/css/app.min.css -->
<link rel="stylesheet" type="text/css" href="./assets/css/style.css" media="screen" />
<!-- endbuild -->
</head>
<body> </body>
<!-- build:js dist/js/app.min.js -->
<script src="./assets/js/foo.js"></script>
<script src="./assets/js/bar.js"></script>
<!-- endbuild -->
</html>
打包后的index.html
<!DOCTYPE html>
<html>
<head>
<title>Usemin test</title>
<link rel="stylesheet" href="dist/css/app.min.css" media="screen"/>
</head>
<body> </body>
<script src="dist/js/app.min.js"></script>
</html>