首先需要安装node.js才能用npm进行安装grunt,如何安装npm这里就不在叙述了。找下谷哥,度娘问下就知道
卸载(-g:全局)
npm uninstall -g grunt
安装cli(-g:全局)
npm install -g grunt-cli
生成package.json到项目目录
npm init
安装grunt 到项目目录
npm install grunt --save-dev
安装插件到项目目录
npm install 插件名称 --save-dev
执行以后package.json会自动变更,无需手动修改
以下是一些常用的插件
grunt-contrib-clean
:删除文件。npm>>
grunt-contrib-compass
:使用compass编译sass文件。npm>>
grunt-contrib-concat
:合并文件。npm>>
grunt-contrib-copy
:复制文件。npm>>
grunt-contrib-cssmin
:压缩以及合并CSS文件。npm>>
grunt-contrib-imagemin
:图像压缩模块。npm>>
grunt-contrib-jshint
:检查JavaScript语法。npm>>
grunt-contrib-uglify
:压缩以及合并JavaScript文件。npm>>
grunt-contrib-watch
:监视文件变动,做出相应动作。npm>>
grunt-contrib-stylus
:stylus编写styl输出css npm>>
配置插件信息【Gruntfile.js】
下面是暂时用到的一些配置,更详细的配置可以参考各插件文档
module.exports = function(grunt) {
// 任务配置,所有插件的配置信息
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
//单纯合并文件
concat: {
options: {
separator: ';'
},
lib_task: {
src: [
'lib/angularjs/angular.min.js',
'lib/angularjs/angular-ui-router.min.js',
],
dest: 'lib.min.js'
}
},
// 压缩合并JS
uglify: {
options: {
//banner: '/*! CNVP[Michael.Z] - ' +
//'<%= grunt.template.today("yyyy-mm-dd") %> */'
},
app_js: {
options: {
mangle: true //不混淆变量名
},
files: {
'app.min.js': ['js/*.js']
}
}
},
// watch插件的配置信息
watch: {
another: {
files: ['js/**/*.js'],
tasks: ['uglify'],
options: {
// Start another live reload server on port 1337
livereload: 1337
}
}
},
jshint: {
options: {
//大括号包裹
curly: true,
//对于简单类型,使用===和!==,而不是==和!=
eqeqeq: true,
//对于首字母大写的函数(声明的类),强制使用new
newcap: true,
//禁用arguments.caller和arguments.callee
noarg: true,
//对于属性使用aaa.bbb而不是aaa['bbb']
sub: true,
//查找所有未定义变量
undef: true,
//查找类似与if(a = 0)这样的代码
boss: true,
//指定运行环境为node.js
node: true,
globals: {
angular: true
}
},
//具体任务配置
files: {
src: ['js/*.js','js/**/*.js']
}
}
});
// 告诉grunt我们将使用插件
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
// 告诉grunt当我们在终端中输入grunt时需要做些什么
grunt.registerTask('default', [
'concat',
'jshint',
'uglify',
/*'watch'*/
]);
};
执行Grunt任务
目录下执行grunt命令即可