SlideShare une entreprise Scribd logo
1  sur  12
Télécharger pour lire hors ligne
GruntJS
Javascript Task Runner
(in a nutshell)
Claudio Mignanti - April 2014
Grunt - Introduction
On these slides I will show you how to master the GruntJS Task Runner program with
example and cross references to a github project.
Grunt is a way to automate operations and to performing repetitive tasks. After the
"configuration" grunt will help you in repetive tasks like minification, compiling, unitest,
etc.
The configuration of GruntJS begins writing the Gruntfile.js file, inside this file we will
define the operations that we need and their dependencies.
Gruntfile.js
module.exports = function (grunt) {
//area 1 - loadding modules
grunt.loadNpmTasks('grunt-contrib-clean');
//area 2 - configure single plugins
grunt.initConfig({
clean: {
'static': ['static/*'],
},
});
//area 3 - register the operations deps
grunt.registerTask('default', ['clean']);
};
The Gruntfile.js by side show the three main session of
the grunt configuration file.
Saving it inside a directory that execute the following
command in the same directory:
$ npm install grunt-contrib-clean --save-dev
$ grunt
The grunt call will show you something like:
$ grunt
Running "clean:static" (clean) task
Done, without errors.
Here we just execute the default registered task defined
inside the third area of the Gruntfile.js, task that is
composed by an array of subsequential operation in this
case the single operation "clean:static"
Grunfile.js
module.exports = function (grunt) {
//area 1 - loadding modules
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-concat');
//area 2 - configure single modules
grunt.initConfig({
clean: {
'static': ['static/*']
},
concat: {
homepage: {
src: ['head.html', 'body.html', 'footer.html'],
dest: 'static/index.html'
}
}
});
//area 3 - register the operations deps
grunt.registerTask('default', ['clean', 'concat']);
};
Grunt is generally extended using plugins, and in this
second example we load two plugins from the npm
repository; to run this example you should run:
$ npm install grunt-contrib-concat --save-dev
This particular plugin is used to concatenate files, a
common operation that generally is used agains js files
but here it is show agains some html files.
The resulting should be:
$ grunt
Running "clean:static" (clean) task
Running "concat:homepage" (concat) task
File "static/index.html" created.
Done, without errors.
This result in a new empty index.html file inside static/
webserver
Workflow with grunt
Grunt is generally used as developer helper tools
that made tasks meanwhile the developer is
coding his app.
A tipical workflow is show by side.
Grunt will manipulate some input files with a
series of task and generate the staging files on
witch the developer can do is work.
In the follow slides I will show you a typical use
case where we use grunt to operate
automatically over some javascript files and html
file using minification and webserver.
htmls
files
js
files
grunt
staging
files
A simple workflow
module.exports = function (grunt) {
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.initConfig({
clean: {
'static': ['static/*']
},
concat: {
homepage: {
src: ['head.html', 'body.html', 'footer.html'],
dest: 'static/index.html'
},
js: {
src: ['lib/*.js', 'my-app.js'],
dest: 'static/app.js'
}
},
connect: {
dev: {
options: {
//point your browser to http://localhost:9000
port: 9000,
base: 'static/'
}
}
}
});
grunt.registerTask('default', ['clean', 'concat', 'connect']);
};
Be side is show a workflow compliant with the previous
slide. Files are manipulated than an instance of connect.
js is executed and you can see the resulting webapp on
port 9000.
Should be clear now that the use this example you
should install some grunt plugins using npm.
Here you should install grunt-contrib-connect using this
command:
$ npm install grunt-contrib-connect --save-dev
What's happen if the developer modify the my-app.js file?
How to automate the update of files?
webserver
Workflow with grunt-watch
The grunt-wacth plugin is used to run some
tasks when files changes, tipically it is used to
run specific tasks when some kinds of files are
modified.
For example if some js files is modified we can
lint, concat and minify all the js files togheter.
Image this situation, the developer is writting his
code, save the project files and grunt will operate
individually meanwhile the developer is switching
from his code editor to the browser.
BIG WIN!
Let see this gruntfile in detail.
htmls
files
js
files
grunt
staging
files
grunt-watch
A workflow with watch
watch: {
webapp: {
files: [ 'libs/*.js' , 'my-app.js' ],
tasks: [ 'concat:js' ]
},
html: {
files: [ '*.html'],
tasks: [ 'concat:homepage' ]
}
}
});
//in area 3
grunt.registerTask( 'default', ['clean', 'concat', 'connect', 'watch']);
To integrate the previous
Gruntfile with the watch
improvment you should add the
piece of code be side inside the
initConfig object.
Please note how different
changes to files triggers different
group of tasks.
Now you can dev your using
app with livereload.
connect is serving the pages in process watch will waiting for changes
based on file type call the
appropriate sub-task
Custom task
You can also write a custom grunt task that is defacto a javascript
function execute inside nodejs enviroment (as grunt itself)
grunt.task.registerTask( 'config', 'compile config from config.js ' , function () {
var fs = require( 'fs');
var config = require( 'config');
if (!fs.existsSync( 'config.json' )) {
fs.writeFileSync( 'config.json' , JSON.stringify(config, null, 2));
}
});
grunt.registerTask( 'default', ['clean', 'config', 'concat', 'watch']);
Here you can see a custom task that generate a config.json file
using the nodejs fs api.
Grunt plugins
Grunt plugins are great to extend and personalize the use of grunt
and you can also write your own plugins using the powerful grunt
api.
If you need to write a plugin I would suggest to start from the task
api and than read at least the files api before start.
Integrate grunt plugins
On http://gruntjs.com/plugins you can found more that 2600 plugin
right now.
Go and explore this new world!
EOF
?
Thanks!

Contenu connexe

Tendances

Improving your workflow with gulp
Improving your workflow with gulpImproving your workflow with gulp
Improving your workflow with gulp
frontendne
 

Tendances (19)

Introduzione a GitHub Actions (beta)
Introduzione a GitHub Actions (beta)Introduzione a GitHub Actions (beta)
Introduzione a GitHub Actions (beta)
 
Puppet Data Mining
Puppet Data MiningPuppet Data Mining
Puppet Data Mining
 
JavaScript code academy - introduction
JavaScript code academy - introductionJavaScript code academy - introduction
JavaScript code academy - introduction
 
GulpJs - An Introduction
GulpJs - An IntroductionGulpJs - An Introduction
GulpJs - An Introduction
 
Workshop - Golang language
Workshop - Golang languageWorkshop - Golang language
Workshop - Golang language
 
Grooscript gr8conf 2015
Grooscript gr8conf 2015Grooscript gr8conf 2015
Grooscript gr8conf 2015
 
Grooscript greach 2015
Grooscript greach 2015Grooscript greach 2015
Grooscript greach 2015
 
Intro to Git for Drupal 7
Intro to Git for Drupal 7Intro to Git for Drupal 7
Intro to Git for Drupal 7
 
Get going with_git_ppt
Get going with_git_pptGet going with_git_ppt
Get going with_git_ppt
 
Git github
Git githubGit github
Git github
 
Coscup x ruby conf tw 2021 google cloud buildpacks 剖析與實踐
Coscup x ruby conf tw 2021  google cloud buildpacks 剖析與實踐Coscup x ruby conf tw 2021  google cloud buildpacks 剖析與實踐
Coscup x ruby conf tw 2021 google cloud buildpacks 剖析與實踐
 
Understanding about git
Understanding about gitUnderstanding about git
Understanding about git
 
GIT - GOOD PRACTICES
GIT - GOOD PRACTICESGIT - GOOD PRACTICES
GIT - GOOD PRACTICES
 
Improving your workflow with gulp
Improving your workflow with gulpImproving your workflow with gulp
Improving your workflow with gulp
 
Grooscript in Action SpringOne2gx 2015
Grooscript in Action SpringOne2gx 2015Grooscript in Action SpringOne2gx 2015
Grooscript in Action SpringOne2gx 2015
 
GraphQL IN Golang
GraphQL IN GolangGraphQL IN Golang
GraphQL IN Golang
 
Let's migrate to Swift 3.0
Let's migrate to Swift 3.0Let's migrate to Swift 3.0
Let's migrate to Swift 3.0
 
Jenkins 2.0 最新事情 〜Make Jenkins Great Again〜
Jenkins 2.0 最新事情 〜Make Jenkins Great Again〜Jenkins 2.0 最新事情 〜Make Jenkins Great Again〜
Jenkins 2.0 最新事情 〜Make Jenkins Great Again〜
 
Будь первым
Будь первымБудь первым
Будь первым
 

En vedette

AFP, Poliovirus, Enteroviruses,
AFP, Poliovirus, Enteroviruses, AFP, Poliovirus, Enteroviruses,
AFP, Poliovirus, Enteroviruses,
Fibamicro1
 
Mr holdins car
Mr holdins carMr holdins car
Mr holdins car
huzguc7k
 
Session plan retail management
Session plan retail managementSession plan retail management
Session plan retail management
rk2its
 
El perfume
El perfumeEl perfume
El perfume
Klad314
 
Mr holdings car
Mr holdings carMr holdings car
Mr holdings car
huzguc7k
 
Happy Birthday MORGAN!!!
Happy Birthday MORGAN!!!Happy Birthday MORGAN!!!
Happy Birthday MORGAN!!!
lbly
 
Help and hoarding by Annette Conway, Psy.D.
Help and hoarding by Annette Conway, Psy.D.Help and hoarding by Annette Conway, Psy.D.
Help and hoarding by Annette Conway, Psy.D.
scott4hlp
 
Help and hoarding
Help and hoardingHelp and hoarding
Help and hoarding
scott4hlp
 
Picobgp - A simple deamon for routing advertising
Picobgp - A simple deamon for routing advertisingPicobgp - A simple deamon for routing advertising
Picobgp - A simple deamon for routing advertising
Claudio Mignanti
 

En vedette (20)

Mr Holdings car
Mr Holdings carMr Holdings car
Mr Holdings car
 
The city of bicycles
The city of bicyclesThe city of bicycles
The city of bicycles
 
AFP, Poliovirus, Enteroviruses,
AFP, Poliovirus, Enteroviruses, AFP, Poliovirus, Enteroviruses,
AFP, Poliovirus, Enteroviruses,
 
Mr holdins car
Mr holdins carMr holdins car
Mr holdins car
 
Your face _farsi_
Your face _farsi_Your face _farsi_
Your face _farsi_
 
Computers
ComputersComputers
Computers
 
Session plan retail management
Session plan retail managementSession plan retail management
Session plan retail management
 
El perfume
El perfumeEl perfume
El perfume
 
Virus y vacunas expo.claudia parra
Virus y vacunas expo.claudia parraVirus y vacunas expo.claudia parra
Virus y vacunas expo.claudia parra
 
(1) siyasal tarih 1923-50
(1) siyasal tarih 1923-50(1) siyasal tarih 1923-50
(1) siyasal tarih 1923-50
 
Mr holdings car
Mr holdings carMr holdings car
Mr holdings car
 
Happy Birthday MORGAN!!!
Happy Birthday MORGAN!!!Happy Birthday MORGAN!!!
Happy Birthday MORGAN!!!
 
мой город
мой городмой город
мой город
 
Help and hoarding by Annette Conway, Psy.D.
Help and hoarding by Annette Conway, Psy.D.Help and hoarding by Annette Conway, Psy.D.
Help and hoarding by Annette Conway, Psy.D.
 
Help and hoarding
Help and hoardingHelp and hoarding
Help and hoarding
 
Crackedpot
CrackedpotCrackedpot
Crackedpot
 
Picobgp - A simple deamon for routing advertising
Picobgp - A simple deamon for routing advertisingPicobgp - A simple deamon for routing advertising
Picobgp - A simple deamon for routing advertising
 
311
311311
311
 
Presentazione tirocinio
Presentazione tirocinio Presentazione tirocinio
Presentazione tirocinio
 
The wright brothers started with a glider before going to powered flight.
The wright brothers started with a glider before going to powered flight.The wright brothers started with a glider before going to powered flight.
The wright brothers started with a glider before going to powered flight.
 

Similaire à Grunt.js introduction

Gradle - small introduction
Gradle - small introductionGradle - small introduction
Gradle - small introduction
Igor Popov
 
Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01
Tino Isnich
 

Similaire à Grunt.js introduction (20)

Get Grulping with JavaScript Task Runners (Matt Gifford)
Get Grulping with JavaScript Task Runners (Matt Gifford)Get Grulping with JavaScript Task Runners (Matt Gifford)
Get Grulping with JavaScript Task Runners (Matt Gifford)
 
OpenCms Days 2012 - Developing OpenCms with Gradle
OpenCms Days 2012 - Developing OpenCms with GradleOpenCms Days 2012 - Developing OpenCms with Gradle
OpenCms Days 2012 - Developing OpenCms with Gradle
 
Automating Front-End Workflow
Automating Front-End WorkflowAutomating Front-End Workflow
Automating Front-End Workflow
 
GradleFX
GradleFXGradleFX
GradleFX
 
Javascript, the GNOME way (JSConf EU 2011)
Javascript, the GNOME way (JSConf EU 2011)Javascript, the GNOME way (JSConf EU 2011)
Javascript, the GNOME way (JSConf EU 2011)
 
Angular Optimization Web Performance Meetup
Angular Optimization Web Performance MeetupAngular Optimization Web Performance Meetup
Angular Optimization Web Performance Meetup
 
Grunt & Front-end Workflow
Grunt & Front-end WorkflowGrunt & Front-end Workflow
Grunt & Front-end Workflow
 
Grunt
GruntGrunt
Grunt
 
Grunt
GruntGrunt
Grunt
 
Grunt
GruntGrunt
Grunt
 
3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdf3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdf
 
Grunt training deck
Grunt training deckGrunt training deck
Grunt training deck
 
Gradle - small introduction
Gradle - small introductionGradle - small introduction
Gradle - small introduction
 
Book
BookBook
Book
 
Modern frontend development with VueJs
Modern frontend development with VueJsModern frontend development with VueJs
Modern frontend development with VueJs
 
Gradle Introduction
Gradle IntroductionGradle Introduction
Gradle Introduction
 
Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01
 
Get Grulping with JavaScript Task Runners
Get Grulping with JavaScript Task RunnersGet Grulping with JavaScript Task Runners
Get Grulping with JavaScript Task Runners
 
Angular performance slides
Angular performance slidesAngular performance slides
Angular performance slides
 
Improving build solutions dependency management with webpack
Improving build solutions  dependency management with webpackImproving build solutions  dependency management with webpack
Improving build solutions dependency management with webpack
 

Plus de Claudio Mignanti (7)

Pycon9 - Paas per tutti i gusti con Dokku and Kubernetes
Pycon9 - Paas per tutti i gusti con Dokku and KubernetesPycon9 - Paas per tutti i gusti con Dokku and Kubernetes
Pycon9 - Paas per tutti i gusti con Dokku and Kubernetes
 
Roma linuxday 2013 - nodejs
Roma linuxday 2013 - nodejsRoma linuxday 2013 - nodejs
Roma linuxday 2013 - nodejs
 
TuxIsAlive
TuxIsAliveTuxIsAlive
TuxIsAlive
 
Elettronica digitale with Example
Elettronica digitale with ExampleElettronica digitale with Example
Elettronica digitale with Example
 
Git for dummies
Git for dummiesGit for dummies
Git for dummies
 
Openwrt, linux e GPIO al LinuxDay 2010 Roma
Openwrt, linux e GPIO al LinuxDay 2010 RomaOpenwrt, linux e GPIO al LinuxDay 2010 Roma
Openwrt, linux e GPIO al LinuxDay 2010 Roma
 
Presentazione Ninux al LinuxDay Roma 2012
Presentazione Ninux al LinuxDay Roma 2012Presentazione Ninux al LinuxDay Roma 2012
Presentazione Ninux al LinuxDay Roma 2012
 

Dernier

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Dernier (20)

presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 

Grunt.js introduction

  • 1. GruntJS Javascript Task Runner (in a nutshell) Claudio Mignanti - April 2014
  • 2. Grunt - Introduction On these slides I will show you how to master the GruntJS Task Runner program with example and cross references to a github project. Grunt is a way to automate operations and to performing repetitive tasks. After the "configuration" grunt will help you in repetive tasks like minification, compiling, unitest, etc. The configuration of GruntJS begins writing the Gruntfile.js file, inside this file we will define the operations that we need and their dependencies.
  • 3. Gruntfile.js module.exports = function (grunt) { //area 1 - loadding modules grunt.loadNpmTasks('grunt-contrib-clean'); //area 2 - configure single plugins grunt.initConfig({ clean: { 'static': ['static/*'], }, }); //area 3 - register the operations deps grunt.registerTask('default', ['clean']); }; The Gruntfile.js by side show the three main session of the grunt configuration file. Saving it inside a directory that execute the following command in the same directory: $ npm install grunt-contrib-clean --save-dev $ grunt The grunt call will show you something like: $ grunt Running "clean:static" (clean) task Done, without errors. Here we just execute the default registered task defined inside the third area of the Gruntfile.js, task that is composed by an array of subsequential operation in this case the single operation "clean:static"
  • 4. Grunfile.js module.exports = function (grunt) { //area 1 - loadding modules grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-concat'); //area 2 - configure single modules grunt.initConfig({ clean: { 'static': ['static/*'] }, concat: { homepage: { src: ['head.html', 'body.html', 'footer.html'], dest: 'static/index.html' } } }); //area 3 - register the operations deps grunt.registerTask('default', ['clean', 'concat']); }; Grunt is generally extended using plugins, and in this second example we load two plugins from the npm repository; to run this example you should run: $ npm install grunt-contrib-concat --save-dev This particular plugin is used to concatenate files, a common operation that generally is used agains js files but here it is show agains some html files. The resulting should be: $ grunt Running "clean:static" (clean) task Running "concat:homepage" (concat) task File "static/index.html" created. Done, without errors. This result in a new empty index.html file inside static/
  • 5. webserver Workflow with grunt Grunt is generally used as developer helper tools that made tasks meanwhile the developer is coding his app. A tipical workflow is show by side. Grunt will manipulate some input files with a series of task and generate the staging files on witch the developer can do is work. In the follow slides I will show you a typical use case where we use grunt to operate automatically over some javascript files and html file using minification and webserver. htmls files js files grunt staging files
  • 6. A simple workflow module.exports = function (grunt) { grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-connect'); grunt.initConfig({ clean: { 'static': ['static/*'] }, concat: { homepage: { src: ['head.html', 'body.html', 'footer.html'], dest: 'static/index.html' }, js: { src: ['lib/*.js', 'my-app.js'], dest: 'static/app.js' } }, connect: { dev: { options: { //point your browser to http://localhost:9000 port: 9000, base: 'static/' } } } }); grunt.registerTask('default', ['clean', 'concat', 'connect']); }; Be side is show a workflow compliant with the previous slide. Files are manipulated than an instance of connect. js is executed and you can see the resulting webapp on port 9000. Should be clear now that the use this example you should install some grunt plugins using npm. Here you should install grunt-contrib-connect using this command: $ npm install grunt-contrib-connect --save-dev What's happen if the developer modify the my-app.js file? How to automate the update of files?
  • 7. webserver Workflow with grunt-watch The grunt-wacth plugin is used to run some tasks when files changes, tipically it is used to run specific tasks when some kinds of files are modified. For example if some js files is modified we can lint, concat and minify all the js files togheter. Image this situation, the developer is writting his code, save the project files and grunt will operate individually meanwhile the developer is switching from his code editor to the browser. BIG WIN! Let see this gruntfile in detail. htmls files js files grunt staging files grunt-watch
  • 8. A workflow with watch watch: { webapp: { files: [ 'libs/*.js' , 'my-app.js' ], tasks: [ 'concat:js' ] }, html: { files: [ '*.html'], tasks: [ 'concat:homepage' ] } } }); //in area 3 grunt.registerTask( 'default', ['clean', 'concat', 'connect', 'watch']); To integrate the previous Gruntfile with the watch improvment you should add the piece of code be side inside the initConfig object. Please note how different changes to files triggers different group of tasks. Now you can dev your using app with livereload. connect is serving the pages in process watch will waiting for changes based on file type call the appropriate sub-task
  • 9. Custom task You can also write a custom grunt task that is defacto a javascript function execute inside nodejs enviroment (as grunt itself) grunt.task.registerTask( 'config', 'compile config from config.js ' , function () { var fs = require( 'fs'); var config = require( 'config'); if (!fs.existsSync( 'config.json' )) { fs.writeFileSync( 'config.json' , JSON.stringify(config, null, 2)); } }); grunt.registerTask( 'default', ['clean', 'config', 'concat', 'watch']); Here you can see a custom task that generate a config.json file using the nodejs fs api.
  • 10. Grunt plugins Grunt plugins are great to extend and personalize the use of grunt and you can also write your own plugins using the powerful grunt api. If you need to write a plugin I would suggest to start from the task api and than read at least the files api before start.
  • 11. Integrate grunt plugins On http://gruntjs.com/plugins you can found more that 2600 plugin right now. Go and explore this new world!