前端自动化Grunt教程

最近在学习Bootstrap,了解一部分之后,发现Bootstrap使用了LESS,好嘛,开始学习LESS,LESS了解部分,发现自动编译工具Grunt,了解Grunt过程发现需要使用node.js的npm工具和语法。。。。。。得,打住吧,先安装node吧,之后再了解。由于本屌丝使用的是win7系统,所以以下教程均在win7下测试。

1.准备工作:安装node.js:http://www.w3cschool.cc/nodejs/nodejs-install-setup.html

新版nodejs自带npm管理工具,可通过命令npm -version查看


如果你之前安装过node,可通过命令将npm更新到最新版:npm install npm@latest

2.安装Grunt-CLI:

npm install -g grunt-cli  带g标识符把grunt命令符植入到系统路径,这样你可以在任何文件目录下运行grunt命令。可通过grunt -version查看是否安装成功。

3.grunt测试:

3.1 新建个项目文件project,project下新建两个文件夹src和dest,src存放手工编写的相应文件,如menu.js与slide.js。dest文件存放grunt运行后的结果。


3.2 在项目project文件下新建package.json文件:
文件内容如下:


保存后进入项目文件下,执行命令npm install下载grunt工具。
前三个警告是由于我们的json文件里没有加入description属性和repository对象,还有README的介绍。可以自行加入。

。。。。。。


完成后会发现我们的project文件下多了个node_modules文件夹,而里面保存的就是我们刚刚在package.json下定义要加载的插件。
3.3 新建Gruntfile.js文件
module.exports = function(grunt) {
	//配置
	grunt.initConfig({
		pkg : grunt.file.readJSON('package.json'),
		//concat插件的用途
		concat : {
			bar : {
				src : ['src/menu.js','src/slide.js'],
				dest : 'dest/main.js'
			}
		},
		//uplify插件的用途
		uglify : {
			options : {
				banner : '/* <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */
'
			},
			build : {
				src : 'dest/main.js',
				dest : 'dest/main.min.js'
			}
		}
	});
	
	//载入concat和uglify插件,分别对于合并和压缩
	grunt.loadNpmTasks('grunt-contrib-concat');
	grunt.loadNpmTasks('grunt-contrib-uglify');
	//注册任务
	grunt.registerTask('default',['concat','uglify']);
};
3.4 运行grunt命令

3.5 此时会发现dest目录下有main.js与main.min.js两个文件。至此大功大功告成。

原文地址:https://www.cnblogs.com/qingguo/p/5686299.html