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

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

####神器 grunt.jscss

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

grunt-contrib-watch

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

grunt-contrib-connect

grunt-contrib-connect,文档上面,它给本身的定义就是一个connect web server,因此,这是一个能够建立服务器的插件。web

正片

建立咱们的工程目录:npm

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

package.json能够用npm init来建立,或者本身建立文件。这个属于npm基础,不了解的本身面壁。在命令行执行如下代码:json

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模块:app

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的配置

相关文章
相关标签/搜索