Grunt is a system for building Web development, but it creates more difficult. In this tutorial, you will learn how to configure Grunt create a modern Web project. When you complete the configuration tutorial, you Gruntfile
will have:
- Copy the files from the source directory to the target directory;
- Delete build file;
- Compiling
Stylus
files and add a prefix to them; - Compilation
CoffeeScript
; - Compression
CSS
andJavaScript
file; - Compilation
Jade
; - When a file is modified to automatically build a source file;
- Developers run server
Grunt has a Chinese version of the official website, if you are interested in Grunt, you can click here to view the relevant Chinese documents.
Start
If you have not started using Grunt, you need to install " Node.js " and " NPM ." You also need to enter a command in the command ends npm install -g grunt-cli
to install Grunt. This allows your system to use anywhere you grunt
command your Grunt.
Create a package.json
file, and add the following:
{
"name": "grunt_tutorial",
"description": "An example of how to set up Grunt for web development.",
"author": "Landon Schropp (http://landonschropp.com)",
"dependencies": {
"grunt": "0.x.x",
"grunt-autoprefixer": "0.2.x",
"grunt-contrib-clean": "0.5.x",
"grunt-contrib-coffee": "0.7.x",
"grunt-contrib-connect": "0.4.x",
"grunt-contrib-copy": "0.4.x",
"grunt-contrib-cssmin": "0.6.x",
"grunt-contrib-jade": "0.8.x",
"grunt-contrib-jshint": "0.6.x",
"grunt-contrib-stylus": "0.8.x",
"grunt-contrib-uglify": "0.2.x",
"grunt-contrib-watch": "0.5.x"
},
"engine": "node >= 0.10"
}
This file defines your project as a NPM
statement bag and your project depends needed. Each statement has its own version number. For example, grunt-contrib-copy:"0.4.x"
tell NPM
install the latest version 0.4 grunt-contrib-copy
package. At your command to run the terminal npm
installation you need to manage plug-ins.
copy
A good script always make the source code and run separate file. Such separation allows you to modify the source file without affecting the script.
Start, you make Grunt from source
copying files in the directory to the build
directory. We need to create a Gruntfile.js
file and copy the following code into this file:
= module.exports function (Grunt) { // configuration tasks grunt.initConfig ({ Copy: { Build: { CWD: 'Source' , the src: [ '**' ], dest: 'Build' , the expand: to true }, } }); // loading tasks grunt.loadNpmTasks ( 'Grunt-contrib-Copy' ); // define task };
Let's break it down. In Node
the need for a module, through modules.exports
to the transfer of the function and the return value. In the Gruntfile
document by modules.exports
telling Node
define Grunt configuration, and returns a function. grunt.initConfig
Is a method, he takes one argument: an object's properties to configure a Grunt mission.
In Grunt configuration, you have added a copy
task. This task has a sub-task, called build
. In Grunt, a plurality of tasks called multitasking . For the copy
task, you do not need this feature, but it still needs to have at least a sub-task.
Grunt mission is to create a sub- file array format . This format is one of a source file format to provide a method Grunt a task. cwd
Directory to the source file is relative, and src
specify the source of similar documents. **
It is a wildcard to match any documents Grunt. dest
Grunt is used to output the results of the task. You will set the build
directory tells Grunt copy the contents to build
the directory. If there is a source/index.html
file, the output configuration build/index.html
file. Finally, you set the expand
parameters for the cake true
to turn on these options.
grunt.loadNpmTasks("grunt-contrib-copy")
Tell Grunt from the grunt-contrib-copy
loaded task package. This gives us a copy
command, you can at your command console by grunt copy
allow replication command.
Clean
Now you have a build
catalog, he is used to complete the clean
task. Then you copy the configuration to which the following:
clean: { build: { src: [ 'build' ] }, },
Like copy
, you set a clean
goal and task configuration, clean
equipped with a src
set up build
, used to remove build
the directory.
Next use grunt.loadNpmTask("grunt-contrib-clean")
, load a clean
job that allows you to run the command terminal grunt clean
command.
grunt.loadNpmTasks('grunt-contrib-clean');
Build
If you have a build
job, you need to delete the old before you copy the new source file build
, it is not very good, let's add a task.
// 定义任务 grunt.registerTask( 'build', 'Compiles all of the assets and copies the files to the build directory.', [ 'clean', 'copy' ] );
This registerTask
method creates a new task. The first parameter build
defines the name of this task. The second is used to describe the task. The last parameter is an array of tasks to be run, this build
task, run clean
the task, and then run copy
the task.
Stylus
Stylus is a CSS preprocessor language. It enhances several functions on CSS, including the addition of variables, functions and nested functions.
stylus: { build: { options: { linenos: true, compress: false }, files: [{ expand: true, cwd: 'source', src: [ '**/*.styl' ], dest: 'build', ext: '.css' }] } },
This task is slightly different from other tasks. This is still build
a sub-task, but it contains two properties: options
and files
. options
Specifies the behavior you want to complete the task. We added two options: compress
to decide whether CSS is compressed and output linenos
selector Stylus add line numbers in the source file.
files
Before formatting documents set some parameters array. After running this task, source
under the directory .styl
file extension compiler output file .css
.
Now stylus
the task is to export the CSS file to build
a directory, there is no reason to copy files to the Stylus build
directory anywhere. Let's modify the copy
configuration to prevent such a thing happen.
copy: {
build: { cwd: 'source', src: [ '**', '!**/*.styl' ], dest: 'build', expand: true },
},
In the beginning of the file path can be prevented Grunt matching patterns. Do not forget to
build
add a task stylus
.
grunt.registerTask(
'build',
'Compiles all of the assets and copies the files to the build directory.',
[ 'clean', 'copy', 'stylus' ]
);
Autoprefixer
Autoprefixer is a stunner Stylus shift after people compiled into CSS, CSS3 properties to add a prefix plugin. He is a powerful library, as Nib and Compass .
Continue to add autoprefixer
configuration:
autoprefixer: {
build: { expand: true, cwd: 'build', src: [ '**/*.css' ], dest: 'build' }
},
I noticed a pattern yet? This configuration is very similar to other tasks. One obvious difference is cwd
and the dest
two are set build
. Used autoprefixer
files and read the output in the same directory.
And in front of the same, you need to load autoprefixer
task.
grunt.loadNpmTask('grunt-autoprefixer');
Not add all of the tasks to the CSS build
, create a style and add a new task will be added to the task build
in.
// 配置任务
grunt.registerTask(
'stylesheets',
'Compiles the stylesheets.',
[ 'stylus', 'autoprefixer' ]
);
grunt.registerTask(
'build',
'Compiles all of the assets and copies the files to the build directory.',
[ 'clean', 'copy', 'stylesheets' ]
);
CSS compression
The client load a group of large CSS file, it will actually slow down the loading time of the site. Fortunately, the grunt-contrib-cssmin
package can be compressed CSS file and merge multiple files into a single file. We begin the configuration again.
cssmin: {
build: { files: { 'build/application.css': [ 'build/**/*.css' ] }
}
},
Use an array of file formats, this configuration uses Grunt's file object format , several files to the specified destination. All build
the CSS files in the output directory to compression build/application.css
.
CSS compression load task package and stylesheets
added to the task.
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.registerTask(
'stylesheets',
'Compiles the stylesheets.',
[ 'stylus', 'autoprefixer', 'cssmin' ]
);
CoffeeScript
CoffeeScript is a JavaScript compiler a strange language. He has a clean, nice syntax, including the class name and hide a lot less than the JavaScript side.
CoffeeScript will be added to your project is easy. First, add to the configuration:
coffee: {
build: { expand: true, cwd: 'source', src: [ '**/*.coffee' ], dest: 'build', ext: '.js' }
},
The CoffeeScript file in the source file, change their extension .js
, and outputs them to the build
directory. Next, grunt-contrib-coffee
the package is loaded task.
grunt.loadNpmTasks('grunt-contrib-coffee');
The scripts
task is loaded into the build
task:
grunt.registerTask(
'scripts',
'Compiles the JavaScript files.',
[ 'coffee' ]
);
grunt.registerTask(
'build',
'Compiles all of the assets and copies the files to the build directory.',
[ 'clean', 'copy', 'stylesheets', 'scripts' ]
);
Again, you need to add an copy
extension, because CoffeeScript file is not copied to the build
directory.
copy: {
build: { cwd: 'source', src: [ '**', '!**/*.styl', '!**/*.coffee' ], dest: 'build', expand: true },
},
Uglify
Like cssmin
, like, Uglify compressed JavaScript file and compressed into a file. Here is his configuration:
uglify: {
build: {
options: {
mangle: false
},
files: {
'build/application.js': [ 'build/**/*.js' ]
}
}
},
Under default, UglifyJS will make your script with a shorter name to replace the variable and function names. If your project code is their own and that was very handy if you want to share to another project, it will cause problems. Set false
'll turn off this behavior.
Like cssmin
tasks, this task also need to add the file object format.
Load task package, and as scripts
the task will uglify
be added to the task:
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.registerTask(
'scripts',
'Compiles the JavaScript files.',
[ 'coffee', 'uglify' ]
);
Clear up
When you run grunt build
, in addition to build/application.css
and build/application.js
beyond all other CSS and JavaScript files are hanging in the build
directory. Since you do not need them, you can add subtasks to remove them, the following is clean
configured:
clean: {
build: { src: [ 'build' ] },
stylesheets: {
src: [ 'build/**/*.css', '!build/application.css' ] },
scripts: {
src: [ 'build/**/*.js', '!build/application.js' ] },
},
When you run this task, if you do not specify which sub-tasks, Grunt will run these tasks. If you run grunt clean
, will perform clean:build
, clean:stylesheets
and clean:scripts
. If you clean
can not delete a file, it just ignores it, this is not a problem.
Note build/application.css
and build/application.js
excluded stylesheets
and scripts
sub-tasks. You do not want to delete them, after all these efforts come to work.
When updating task, subtasks adaptation:
// define the tasks
grunt.registerTask(
'stylesheets',
'Compiles the stylesheets.',
[ 'stylus', 'autoprefixer', 'cssmin', 'clean:stylesheets' ]
);
grunt.registerTask(
'scripts',
'Compiles the JavaScript files.',
[ 'coffee', 'uglify', 'clean:scripts' ]
);
grunt.registerTask(
'build',
'Compiles all of the assets and copies the files to the build directory.',
[ 'clean:build', 'copy', 'stylesheets', 'scripts' ]
);
Jade
Jade is the HTML template language. By grunt-contrib-jade
the package Jade
added to your project:
jade: {
compile: {
options: {
data: {}
},
files: [{
expand: true,
cwd: 'source',
src: [ '**/*.jade' ],
dest: 'build',
ext: '.html'
}]
}
},
Like stylus
and coffee
tasks, jade
configuration also uses an array of files. In the options
inner set data
target. When Jade file compiled, the object passed to each template. This is very convenient, for example, create separate development or dynamically generated content.
And in front of the same, you need to copy
add an extension:
copy: {
build: { cwd: 'source', src: [ '**', '!**/*.styl', '!**/*.coffee', '!**/*.jade' ], dest: 'build', expand: true },
},
Do not forget to build
add the grunt-contrib-jade
task:
grunt.loadNpmTasks('grunt-contrib-jade');
grunt.registerTask(
'build',
'Compiles all of the assets and copies the files to the build directory.',
[ 'clean:build', 'copy', 'stylesheets', 'scripts', 'jade' ]
);
Watch
Your Gruntfile now has been very strong, but not very good, because every time you have to go run grunt build
. Use grunt-contrib-watch
, you do not need every run. Let's configure one of these tasks, you will see the source code, and automatically build their changes.
watch: {
stylesheets: { files: 'source/**/*.styl', tasks: [ 'stylesheets' ] },
scripts: {
files: 'source/**/*.coffee', tasks: [ 'scripts' ] },
jade: {
files: 'source/**/*.jade', tasks: [ 'jade' ] },
copy: {
files: [ 'source/**', '!source/**/*.styl', '!source/**/*.coffee', '!source/**/*.jade' ], tasks: [ 'copy' ] }
},
stylesheets
, scripts
And jade
subtasks can be monitored Stylus, CoffeeScript and Jade file changes and run their respective mandates. In the copy
test all the remaining tasks in the file and copy it to build
the directory.
Again, you need to load Grunt mission.
grunt.loadNpmTasks('grunt-contrib-watch');
Developer Server
No Web server development environment is incomplete. grunt-contrib-connect
Package is a full-featured static file server for your project is very perfect.
connect: {
server: { options: { port: 4000, base: 'build', hostname: '*' }
}
},
Your host server configuration build
directory on the 4000 port. Under default, the connection to the server on your local host is the localhost
. You can set up hostname
to *
access the server from anywhere.
And in front of the same, you need to add the item to the task Loads and NPM tasks.
grunt.loadNpmTasks('grunt-contrib-connect');
If you try to terminal in order to run grunt connect
, the server is running, then stop immediately. This is because by default, Grunt connet
the task will not run forever, you need to learn how to fix this problem.
default
Running a single task among all the tasks, it is not perfect. default
Tasks are set as follows:
grunt.registerTask(
'default',
'Watches the project for changes, automatically builds them and runs a server.',
[ 'build', 'connect', 'watch' ]
);
default
Run task build
to create an initial build
, and then it starts to connect to the server, it will be the last run watch
, monitor file changes and rebuild. Because watch
always running, so the server has been running. Running on your console grunt
, and then to http: // localhost: 4000 to view your project.
to sum up
In this tutorial we have discussed a lot, but there are many things you can do Grunt. For a complete list of plug-Grunt, you can view Grunt Plugin website .
Further reading
- Grunt Chinese community
- Task management tool Grunt
- Getting started-grunt Getting Started
- Getting Started task configuration in detail -grunt
- Common plug-ins using -grunt Getting Started Guide (on)
- Grunt.js combat in the front end of the project
- Meet Grunt: The Build Tool for JavaScript
- Grunt by Example - A Tutorial for JavaScript's Task Runner
- Getting Started With Grunt & Bower
- Get Up And Running With Grunt.js
Sign Language Translator: whole lines for translation in accordance with the original, and slightly personal understanding of technology in the translation process. If there is wrong with the translation, please also friends, colleagues pointing. Thank you!
English original: Http://Www.Sitepoint.Com/writing-awesome-build-script-grunt/
Chinese translation: http://www.w3cplus.com/tools/writing-awesome-build-script-grunt.html
Reproduced in: https: //www.cnblogs.com/JoannaQ/p/3360454.html