再探 butterfly.js - grunt.js篇(一)

##再探 butterfly.js - grunt.js篇(一)

####神器 grunt.js

久仰grunt.js的大名,学习grunt.js一直是我todo List的第一位。趁着新春佳节来临之际(打酱油的日子),就来填了这个坑,完了这个心愿。 grunt.js的强大,强大在于它拥有很多用途丰富的插件,和不同插件之间的联动实现更牛逼的功能。 这里默认大家已经安装了npm和会用npm install等指令,就不详细讲了。下面讲用到grunt-contrib-watchgrunt-contrib-connect实现改动代码自动刷新浏览器,而不用手动按F5或者ctrl+R来刷新浏览器。也会将这个酷炫的测试功能应用于butterfly.js的应用开发之中。

grunt-contrib-watch

grunt-contrib-watch,这个插件超级强大,基本上,我见到用grunt.js的应用开发,没有那个不用到grunt-contrib-watch。其功能就是:监测指定文件的改动包括:html、css、js,当指定的文件有改动(保存后),就会触发task

grunt-contrib-connect

grunt-contrib-connect,文档上面,它给自己的定义就是一个connect web server,所以,这是一个可以创建服务器的插件。

正片

创建我们的工程目录:

myproject
  ┣app
    ┣butterfly
    ┗main
      ┣theme.css
      ┣index.html
      ┗index.js
  ┣package.json
  ┗Gruntfile.js

package.json可以用npm init来创建,或者自己创建文件。这个属于npm基础,不了解的自己面壁。在命令行执行以下代码:

npm install grunt --save-dev
npm install grunt-contrib-connect --save-dev
npm install grunt-contrib-watch --save-dev

上面的--save-dev是两根--的,不知道为什么被吞了一根,这三行代码,分别安装了gruntgrunt-contrib-connectgrunt-contrib-watch。 编辑Gruntfile.js,这个文件是Grunt.js的核心,所有Grunt.js执行的任务都在这里控制,Grunt.js的原始状态应该是这样的:

module.exports = function(grunt){
	pkg: grunt.file.readJSON('package.json'),
	grunt.initConfig({
		//...
	});
}

先设置connect模块:

connect: {
	options: {
		port: 9000,
		hostname: 'localhost',
		livereload: 35729
	},
	server: {
		options: {
			open: {target:'http://localhost:9000/main/index.html'},
			base: ['app']
		}
	}
}

再设置watch模块:

watch: {
	livereload: {
		options: {
			livereload: true
		},
		files: ['app/main/index.html','app/main/theme.css', 'app/main/index.js']
	}
}

最后设置task

module.exports = function(grunt){
	pkg: grunt.file.readJSON('package.json'),
	grunt.initConfig({
		connect: {
			options: {
				port: 9000,
				hostname: 'localhost',
				livereload: 35729
			},
			server: {
				options: {
					open: {target:'http://localhost:9000/main/index.html'},
					base: ['app']
				}
			}
		},
		watch: {
			livereload: {
				options: {
					livereload: true
				},
				files: ['app/main/index.html','app/main/theme.css', 'app/main/index.js'] //监测文件列表
			}
		}
	});

	grunt.loadNpmTasks('grunt-contrib-connect');
	grunt.loadNpmTasks('grunt-contrib-watch');

	grunt.registerTask('default', ['connect:server', 'watch'])
}

编辑完成后,在命令行输入gruntgrunt.js通过grunt-contrib-connect创建一个服务器,localhost:9000(域名和端口在options设置),执行命令后,你会发现浏览器自动打开了http://localhost:9000/main/index.html。如果没有报错,就算是大功告成了。这时候你可以改动一下index.htmltheme.css或者是index.jsvery good。我们解放了F5这个按钮了。

其实,这个只是grunt.js的一个小功能,grunt.js强大得很,这里先挖个坑,后续会和大家分享grunt.js的其他模块和更加详细的Gruntfile.js的配置

转载于:https://my.oschina.net/u/2287563/blog/378517

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值