Grunt Contrib Watch Example

http://www.thegeekstuff.com/2014/10/grunt-contrib-watch-automate/


frameborder="0" hspace="0" marginheight="0" marginwidth="0" scrolling="no" tabindex="0" vspace="0" width="100%" id="I0_1444864348861" name="I0_1444864348861" src="https://apis.google.com/u/0/se/0/_/+1/fastbutton?usegapi=1&size=medium&origin=http%3A%2F%2Fwww.thegeekstuff.com&url=http%3A%2F%2Fwww.thegeekstuff.com%2F2014%2F10%2Fgrunt-contrib-watch-automate%2F&gsrc=3p&jsh=m%3B%2F_%2Fscs%2Fapps-static%2F_%2Fjs%2Fk%3Doz.gapi.zh_CN.lH2ap3vtVyM.O%2Fm%3D__features__%2Fam%3DAQ%2Frt%3Dj%2Fd%3D1%2Ft%3Dzcms%2Frs%3DAGLTcCPEsdOZWsXpfvwDBv4ML6KSwYR8pA#_methods=onPlusOne%2C_ready%2C_close%2C_open%2C_resizeMe%2C_renderstart%2Concircled%2Cdrefresh%2Cerefresh&id=I0_1444864348861&parent=http%3A%2F%2Fwww.thegeekstuff.com&pfname=&rpctoken=50232353" data-gapiattached="true" title="+1" style="margin: 0px; padding: 0px; word-wrap: break-word; display: block; max-width: 100%; position: static; top: 0px; width: 90px; border-style: none; left: 0px; visibility: visible; height: 20px;">
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.thegeekstuff.com%2F2014%2F10%2Fgrunt-contrib-watch-automate%2F&send=false&layout=button_count&width=450&show_faces=false&action=like&colorscheme=light&font&height=21" scrolling="no" frameborder="0" allowtransparency="true" style="margin: 0px; padding: 0px; word-wrap: break-word; display: block; max-width: 100%; border-style: none; border-width: initial; overflow: hidden; width: 450px; height: 21px;">
id="twitter-widget-0" scrolling="no" frameborder="0" allowtransparency="true" class="twitter-share-button twitter-share-button-rendered twitter-tweet-button" title="Twitter Tweet Button" src="http://platform.twitter.com/widgets/tweet_button.a428ab2e859e8008e0df5404770eb017.en.html#_=1444864349309&count=horizontal&dnt=false&id=twitter-widget-0&lang=en&original_referer=http%3A%2F%2Fwww.thegeekstuff.com%2F2014%2F10%2Fgrunt-contrib-watch-automate%2F&size=m&text=How%20to%20Automate%20Tasks%20using%20Grunt%20Contrib%20Watch%20Example%20(Automatic%20CSS%20Minification%20Example%20using%20Grunt)&type=share&url=http%3A%2F%2Fwww.thegeekstuff.com%2F2014%2F10%2Fgrunt-contrib-watch-automate%2F" style="margin: 0px; padding: 0px; word-wrap: break-word; display: block; max-width: 100%; position: static; visibility: visible; width: 81px; height: 20px;">

As we discussed earlier, using grunt, during your development process, you can execute tasks automatically in the background.

This is helpful in web and mobile UI development process where html, css and javascript are part of the tech stack.

This article covers this specific example scenario: Anytime you modify a css file in your development project, you would like grunt to automatically execute the minification routine on that css file.

The following are few high-level benefits of automating tasks during development process:

  • Avoids manual repetition of same task, which saves time and effort, which in-turn keeps you focused on other important development process.
  • Keeps the configured process abstract.
  • Reduces the probability of errors in configured tasks

We can automate various tasks by using various plug-in with grunt, when the appropriate files are added, modified or deleted.

In this article, we’ll take a practical example of automating css minification using grunt-contrib-watch.

1. Install Grunt Contrib Watch

First, you should have “node.js” installed, and npm project configured with the “Gruntfile.js” for css minification task. Follow the steps in our Grunt install and configure article to do that.

Next, install the “grunt-contrib-watch” package. From commnad line, cd to your project folder, and execute the following command:

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

The above command will install the plugin with the respective entry done in the “package.json” for the npm project dependency listing.

2. Edit the Gruntfile.js

Edit the “Gruntfile.js” to use the plugin. This will also configure the tasks to be watched by it, and automate them on certain events.

In the “Gruntfile.js”, add a task named “watch” under “grunt.initConfig( )” method as shown below. Use proper json format:

watch: {
	scripts: {
		files: './css/*.css',
		tasks: ['default'],
		options: {
			spawn:false,
			event:['all']
		},
	},
},

The following configurations are done in the above snippet of ‘json':

  • Key ‘files’ carries the path of files to be watched.
  • Key ‘tasks’ carries the task to be executed.
  • Key ‘options’ carries all available configuration parameters.
  • Key ‘spawn’ defines whether to seed/repeat the task continuously or not.
  • Key ‘event’ carries the event on which the task is to be triggered. By default it is ‘all’. It can be set ‘changed’, ‘added’ and ‘deleted’ as well.

There are lot more parameter which you can configure here. You can get an idea about it by going through the documentation of it given its git hub repo. We are here covering only the basic required configuration for demo purpose and avoid the complexity in getting it conveyed.

3. Load the Plugin

Load the plugin using “grunt-contrib-watch( )” method.

It can be done by adding the following line in the wrapper function:

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

After this step “Gruntfile.js” will be look as shown below:

module.exports = function(grunt){
	// Initializing configuration objects
	grunt.initConfig({

		// specifying the settings for css file minification
		cssmin : {
			minify : {
				expand : true,
				cwd : './css/',
				src : [ '*.css', '!*.min.css' ],
				dest : './css/',
				ext : '.min.css'
			}
		},

		//specifying the settings for watch
		watch: {
			scripts: {
				files: './css/*.css',
				tasks: ['default'],
				options: {

					spawn:false,
					event:['all']
				},
			},
		},
	});

	// Loading the 'grunt-contrib-cssmin' package.
	grunt.loadNpmTasks('grunt-contrib-cssmin');

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

	// Registering css minification as a default task
	grunt.registerTask( 'default', [ 'cssmin' ] );
}

4. Execute Watch Task for Automation

Execute the command “grunt watch” at the command prompt from your project folder.

# grunt watch
	Running "watch" task

To see this in action, make some changes to your files and look for the log in terminal/command prompt. You will find that, as we configured, “cssmin” task is run automatically on addition, modification or deletion of the configured file in the path.

In the following example, when I changed the file css/style.css, the grunt automatically recognized it and executed the minify routine to minify the style.css routine.

	Running "watch" task
	Waiting...
	>> File "css\style.css" changed.

	Running "cssmin:minify" (cssmin) task
	File css/style.min.css created: 57.58 kB ? 49.39 kB

	Running "watch" task
	Completed in 0.091s at Fri Jul 18 2014 22:59:50
 	Waiting...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值