Inthis article I will go through:
-Grunt环境配置
-Grunt相关组件安装
-一个简单的Grunt例子
What needed 配置环境
-安装 NodeJS 并且设置全局变量
-打开NodeJs console 运行‘npm install’ 检查当前环境是否配置正确
-"npm install -g grunt-cli"cli(Command Line Interface), -g will install it globally cli是grunt命令入口
Hot to use Grunt:
新建文件夹,并从console进入到这个文件夹中。这里需要package.json 和Gruntfile.js 两个文件作为项目的开始,下面是这两个文件的说明:
package.json文件 (two ways to createit)
-Createfrom 'grunt-init' template
This would need first 'npm install grunt-init'
-'npminit, follow the prompts and enter the project information
This is much easier as below:
在下一步前要安装Grunt plugin, 具体做法如下:
'npminstall <Module> --save-dev'
e.g.:
npminstall grunt --save-dev
npminstall grunt-contrib-uglify --save-dev
Package.jsonfile will be auto updated after run the commands.
Gruntfile.js文件
Whatthe file has:
-The"wrapper" function
-Projectand task configuration
-LoadingGrunt plugins and tasks
-Customtasks
Let'shave a sample to quick go through this, content of the file as below:
module.exports=function(grunt){
grunt.initConfig({
//readdata from package.json, so that pkg can be used as data resources here
pkg:grunt.file.readJSON('package.json'),
//<%=%> can be used as place holder where it's content could be changed bywhatever imported.
//uglifyis one of the grunt plugin
uglify:{
options:{
banner:'/*!<%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %>*/\n'
},
build:{
src:'src/<%=pkg.name %>.js',
dest:'build/<%=pkg.name %>.min.js'
}
}
});
//LoadingGrunt plugins and tasks
//plugin name could be found from package.json file
//enablethe plug in by using
grunt.loadNpmTasks('grunt-contrib-uglify');
//Customtasks
//definethe default task as uglify, and uglify is from initConfig uglify above.
grunt.registerTask('default',['uglify']);
//anotherbasid task which will not use any plugin
grunt.registerTask('logInfo','Loginformation from console',function(){
grunt.log.write('Thisis output from grunt task LogInfo').ok();
});
};
这些都做完后就可以从Console窗口运行 ‘grunt logInfo’了!