ArticleYou can also find it on my GitHub to make the layout more friendly: grunt from getting started to custom project templates
1. Introduction to grunt 1. Grunt is a magic horse
Task-based command line build tool (for JavaScript Projects)
Link: http://gruntjs.com/
2. Reasons for using GRUNT
Front-end tools are quite varied. Before introducing grunt, we should first ask ourselves:
- What can grunt help us solve?
- Are there other more suitable alternatives?
3. What problems does grunt solve for us?
As a developer, we have seen many fancy but not practical tools with functions. However, we seldom use a tool because it has powerful functions. More often, because we have encountered some problems at work, and a tool just helped us solve these problems.
Suppose we haveImweb_proj
Project, which consists of two functional modules:Modulea
,Moduleb
. Looking back, as a front-end developer, what is our workflow from Functional Development to product launch:
Before entering the coding work, you must make some preparations:
- Create directory
Imweb_proj
, Index.html is the main portal. Under the root directory, three new directories, JS, CSS, and IMG, are created to store JS files, CSS files, and images respectively.
- Create a main under imweb_proj/Js. as the entry to the main project logic, add modulea. JS and modueb. JS. By the way, we cannot put our basic component badjs. JS, simple. JS, nohost. JS forgot
- Create a new reset.cssunder imweb_proj/cssand use modulea.css、leb.css
The product is coming soon. Preparations before the launch are also not sloppy.
Jshint
-- Check JSCodeNormalization to avoid pitfalls like implicit global variables
Concat
-- Merge JS files to reasonably reduce the number of requests and increase the loading speed
Cssmin
-- CSS file merging to reasonably reduce the number of requests and increase the loading speed
Uglyfy
-- Compress the file to reduce the file size and increase the loading speed on the user side.
Qunit
-- Unit testing improves the maintainability of the project. Combined with recursive testing, potential problems can be detected as early as possible.
- ...
Are the above scenarios very familiar? Repetitive and boring work takes us too much time and forgets who said that when we repeat one thing more than three times, we should consider automating IT.
Grunt was born to solve the above problems. It turned the complex tasks mentioned above, such as project structure generation, jshint check, file merging, compression, and unit testing, into automated tasks, one-click solution.
4. Other reasons for using GRUNT
- Rich documentation: detailed instructions for use, from getting started to advanced customization, very detailed
- Rich plug-ins: You can find common tasks that you can think.
- CommunityActive: grunt's development team is still very hardworking, and the Community is highly active.
5. Are there other more suitable alternatives?
Of course there are many, ant, Yeoman, Mod, Fiddler + Willow + qzmin, etc.
Ii. Use grunt from scratch
Reference: http://gruntjs.com/getting-started
Grunt can be used in two scenarios:
- Maintain the existing grunt project-the configured project. The following describes the jquery plugin project as an example to briefly understand the basic structure of the next grunt project;
- The newly created grunt project, including creating the project directory structure and configuring the grunt task. The existing grunt template or custom template can be used here; the following describes how to create a ** front-end basic project structure of the imweb team ** using a custom template **
1. Environment and dependencies
Grunt and grunt plug-ins are installed and managed through NPM, So first you have to install the node environment, do not repeat, see http://nodejs.org/
2. Version
Note: To solve the problem of coexistence of multiple versions0.4.x
At the beginning of the version, grunt and corresponding plug-ins must be installed independently for each project. The versions are as follows:
- Grunt
0.4.x
- Nodejs
> = 0.8.0
3. Uninstall grunt of earlier versions (version <0.4.0)
Grunt versions from 0.3.x to 0.4.x are greatly changed, mainly to solve the problem of coexistence of grunt multi-version. If you are interested, you can find out. If 0.3.x is installed, uninstall it first.
NPM uninstall-G GRUNT
4. Install grunt-cli
The main function of grunt-CLI is to run the grunt command. With-G, it can be run in any directory without expansion.
NPM install-G grunt-cli
5. Install grunt-init
Grunt-init is a scaffold tool that can help you automate project creation, including the directory structure of the project and files in each directory. The specific situation depends on running the template specified by grunt-init and your answers to the question during creation. This function is briefly described below.
Run the following command to install grunt-init,
NPM install-G grunt-init
Next, we will first install the jquery plugin template to demonstrate the installation of the gurnt template, the creation of the project, and the directory structure of a grunt project.
Iii. jquery plugin example: how to create a project and run a grunt task using an existing Template
Reference connection: http://gruntjs.com/project-scaffolding
1. Install the jquery plugin Template
The following command can view the officially maintained grunt Template
Grunt-init -- Help
Run the following command to install the jquery Template
Git clone git@github.com: gruntjs/grunt-init-jquery.git ~ /. Grunt-init/jquery
2. Create a project based on the jquery plugin Template
In the previous step, we have installed the jquery template, and then run the following command to install the jquery project.
Grunt-init jquery
Follow the instructions to answer the following questions and complete the Project Creation
Please answer the following: [?] Project name (TEST) demojquery [?] Project title (demojquery) [?] Description (the best jquery plugin ever.) Just for test [?] Version (0.1.0) 1.0.0 [?] Project git repository (GIT: // github.com/root/test.git) [?] Project homepage (https://github.com/root/test) [?] Project issues tracker (https://github.com/root/test/issues) [?] Licenses (MIT) [?] Author name (none)ProgramYuanxiaoka [?] Author email (none) [?] Author URL (none) http://chyingp.cnblogs.com [?] Required jquery version (*) 1.9.0 [?] Do you need to make any changes to the above before continuing? (Y/n) N
The project directory structure is as follows:
// Project directory structure-RW-r -- 1 root staff 1670 5 9 15:13 contributing. MD-RW-r -- 1 root staff 559 5 9 15:13 demojquery. jquery. JSON-RW-r -- 1 root staff 2184 5 9 15:13 gruntfile. JS-RW-r -- 1 root staff 1053 5 9 license-Mit-RW-r -- 1 root staff 543 5 9 readme. mddrwxr-XR-x 5 root staff 170 5 9 libs-RW-r -- 1 root staff 423 5 9 package. jsondrwxr-XR-x 4 root staff 136 5 9 srcdrwxr-XR-x 5 root staff 170 5 9 Test
From the preceding directory structure, we can see the functions of various directories and files. Note that two files are gruntfile. JS, package. JSON. Both files must be stored in the project and directory. The following will be a little detailed introduction:
- Gruntfile. jsGrunt configuration information of the project, including module dependency and task definition
- Package. JSONThe dependency information of the Project node module, which is mainly generated based on gruntfile.
Other files that are not required by the grunt project can be ignored for the moment.
3. Run the grunt task
First, run the following command to install the required node module.
NPM install
Enter the following command to run the grunt task
Grunt
Output: Done
Running "jshint: gruntfile" (jshint) task> 1 file lint free. Running "jshint: SRC" (jshint) task> 1 file lint free ....
4. How to Create package. JSON
Method 1: run the following command to create the basic package. JSON file 2 ''' by gradually answering the question '''
NPM install
Method 2: Create an empty package. JSON file, copy the following content, and modify it as needed.
{"Name": "helloproj", "version": "0.1.0", "devdependencies": {"grunt ":"~ 0.4.1 "," Grunt-contrib-jshint ":"~ 0.1.1 "," Grunt-contrib-nodeunit ":"~ 0.1.2 "}}
After creating package. JSON, run the following command to install the required plug-in:
NPM install
5. How to install GRUNT
Run the following command to installLatest Version
Grunt
NPM install grunt -- save-Dev
6. Create gruntfile. js
The format of the configuration file for gruntfile. JS is not complex. However, at the beginning, the configuration file may be in the fog and can be modified using the official example. Reference: http://gruntjs.com/sample-gruntfile
module. exports = function (grunt) {// project configuration information, which is used only for demonstration purposes. initconfig ({PKG: grunt. file. readjson ('package. JSON '), uglify: {// compressed file build: {SRC: 'src/<% = PKG. name %>. js', DEST: 'build/<% = PKG. name %>. min. js' }}, Concat: {// merge file JS: {SRC: ['js/modulea. js', 'js/moduleb. JS '], DEST: 'dist/JS/moduleA-moduleB.js'}, CSS: {SRC: ['dist/CSS/modulea.css ', 'dist/CSS/moduleb.css'], DEST: 'dist/CSS/moduleb.css '}}}); // load the uglify plugin to complete the compression task grunt. loadnpmtasks ('grunt-contrib-uglify '); // load the Concat plug-in to complete the file merge task grunt. loadnpmtasks ('grunt-contrib-concat'); // default task. If the grunt command is run and the task is not specified later, or is defalut, run the grunt. registertask ('default', ['concat', 'uglify ']) ;};
In fact, this method is still a little troublesome. The Grunt team is still more user-friendly. For gruntfile, a separate plug-in is provided, which frees us from repetitive work. I will discuss it later.
Iv. imweb_template: Custom template to create the front-end Project Skeleton exclusive to the imweb team. 1. Download the official grunt sample template.
Download link: https://github.com/gruntjs/grunt-init-jquery
Open the downloaded sample directory and you can see the following content:
-Rwxr-XR-x @ 1 casperchen staff 877 2 18 readme. MD-rwxr-XR-x @ 1 casperchen staff 138 2 18 Rename. jsondrwxr-XR-x @ 10 casperchen staff 340 2 18 root-rwxr-XR-x @ 1 casperchen staff 3521 2 18 template. JS
Brief Introduction:
Template. js
The main template file is very important! The main content is: the question to be answered during project creation, the grunt module on which the project depends (generate package. JSON based on this)
Rename. JSON
The directory/file rename rules for the current template are not described in detail.
Root/
Important! When the file in this directory is generated using this template, all the files in the root directory will be copied to the project.
2. Before creating a custom project
DownloadGrunt-init-jquery-Master
RenameImweb_template
And then we will start our template customization journey! In view of this piece of content is too much, do not explain in detail, directly paste the modified file, you can be more intuitive, If you need in-depth understanding, you can view the relevant link: http://gruntjs.com/project-scaffolding
3. Modify imweb_template/template. js
Below are some of the most common content of template. JS, including:
Exports. Description
Brief Introduction to the template
Exports. Notes
Information printed on the console before answering project-related questions
Exports. After
Information printed on the console before answering project-related questions
Init. Process
Questions to be answered during project Creation
Init. writepackagejson
Generate package. JSON for grunt and NPM
/** Template Name * https://gruntjs.com/** copyright information * licensed under the MIT license. */'use strict '; // brief introduction to the template exports. description = 'create an imweb exclusive template with file merging and compression! '; // The exports information printed on the console before you start to answer questions about the project. notes = 'position of this section: Before answering various project-related information, '+' \ n \ n' + 'can be entered one by one, if you do not want to fill in, you can directly enter and skip '; // after you finish answering the project-related questions, the information displayed on the console exports. after = 'the main project framework has been set up, now you can run '+' \ n \ n' + '1. NPM install the node module on which the project depends \ n' +' 2. Grunt runs the task, including File compression, merge, and validation \ n \ n'; // If grunt-init is run in that directory, if a directory or file meets the specified waron mode, a warning is triggered to prevent the user from accidentally overwriting the file in the current directory. Generally, all files are *. If you want to run them forcibly, -- force // example: grunt-init -- force imweb_template exports. wa Rnon = '*'; // The actual init template. exports. template = function (grunt, init, done) {init. process ({type: 'imweb'}, [// question init. prompt ('name'), init. prompt ('title'), init. prompt ('description', 'imweb Project Skeleton '), init. prompt ('version', '1. 0.0 '), init. prompt ('author _ name'), init. prompt ('author _ email '),], function (ERR, props) {props. KEYWORDS = []; // the object to be copied and processed. You do not need to modify this syntax. var files = init. Filestocopy (props); // The files actually modified and processed. noprocess indicates that init is not processed. copyandprocess (files, props, {noprocess: 'libs/** '}); // generate a package. JSON for grunt and NPM to use init. writepackagejson ('package. JSON ', {Name: 'imweb-proj', version: '0. 0.0-ignored ', npm_test: 'grunt qunit', node_version:'> = 0.8.0 ', devdependencies: {'grunt-contrib-jshint ':'~ 0.1.1 ', 'grunt-contrib-qunit ':'~ 0.1.1 ', 'grunt-contrib-concat ':'~ 0.1.2 ', 'grunt-contrib-uglify ':'~ 0.1.1 ', 'grunt-contrib-cssmin ':'~ 0.6.0 ', 'grunt-contrib-Watch ':'~ 0.2.0 ', 'grunt-contrib-clean ':'~ 0.4.0 ',},}); // all done! Done ();});};
4. Modify imweb_template/rename. JSON
The role of reame. JSON is relatively simple. It defines the path ing relationship when the file is copied to the actual project from the root directory.Sourcepath: destpath
. Sourcepath is relative to the root path, while destpath is relative to the actual project path.
PS: When destpath is false, files corresponding to sourcepath will not be copied to the project.
{"Src/*. js": "JS/*. js", "test/test.html": "Test/test.html "}
5. imweb_template/root directory
Go to the root directory and you will see many files. Among them, gruntfile. js and readme. md
- Configure the basic tasks, such as jshint, Concat, and uglify, of the gruntfile. js project. Other tasks can be expanded by yourself.
- Readme information of the readme. md project. A clear readme is very important.
-Rwxr-XR-x @ 1 casperchen staff 2408 5 10 gruntfile. JS-rwxr-XR-x @ 1 casperchen staff 605 2 18 readme. mddrwxr-XR-x 4 casperchen staff 136 5 9 cssdrwxr-XR-x @ 8 casperchen staff 272 5 9 jsdrwxr-XR-x @ 5 casperchen staff 170 2 18 libsdrwxr- XR-x @ 5 casperchen staff 170 2 18 test
6. Modify gruntfile. js
Modify the gruntfile. js file as follows. It should be easy to understand children's shoes that are familiar with the qzmin configuration file.
'Use strict '; module. exports = function (grunt) {// project configuration. grunt. initconfig ({// metadata. PKG: grunt. file. readjson ('package. JSON '), banner :'/*! <% = PKG. title | PKG. name %>-v <% = PKG. version %>-'+' <% = grunt. template. today ("yyyy-mm-dd") %> \ n' + '* copyright (c) <% = grunt. template. today ("YYYY") %> <% = PKG. author. name %>; '+' */\ n', // job configuration information clean: {// files: ['dist']}, concat: {// File compression js_and_css: {files: {// JS file merging 'dist/JS/base. js': ['js/simple. js', 'js/badjs. js', 'js/nohost. js'], 'dist/JS/main. js': ['js/modulea. js', 'js/moduleb. JS ''js/main. js'], // css file merging 'dist/CSS/style.css ': ['css/reset.css', 'css/modulea.css ', 'css/moduleb.css']}, uglify: {// JS File compression JS: {files: {'dist/JS/base. min. js': ['dist/JS/base. js'], 'dist/JS/main. min. js': ['dist/JS/main. js'] }}, cssmin: {// css File compression CSS: {files: {'dist/CSS/style.min.css ': ['dist/CSS/style.css '] }}, qunit: {// unit test. Files: ['test/**/* is not enabled in this example /**/*. HTML ']}, jshint: {// file verification. gruntfile: {options: {jshintrc:' is not enabled in this example :'. jshintrc '}, Src: 'gruntfile. js'}, Src: {options: {jshintrc: 'js /. jshintrc '}, Src: ['js /**/*. js']}, test: {options: {jshintrc: 'test /. jshintrc '}, Src: ['test /**/*. js'] }}, watch: {// watch task, monitors file changes in real time, and compiles gruntfile: {files: '<% = jshint. gruntfile. SRC %> ', tasks: ['jshint: gruntfile']}, Src: {files: '<% = jshint. SRC. SRC %> ', tasks: ['jshint: src', 'qunit']}, test: {files: '<% = jshint. test. SRC %> ', tasks: ['jshint: test', 'qunit'] }},}); // load various grunt plug-ins to complete the task grunt. loadnpmtasks ('grunt-contrib-clean'); grunt. loadnpmtasks ('grunt-contrib-concat'); grunt. loadnpmtasks ('grunt-contrib-uglify '); grunt. loadnpmtasks ('grunt-contrib-cssmin'); grunt. loadnpmtasks ('grunt-contrib-qunit '); grunt. loadnpmtasks ('grunt-contrib-jshint'); grunt. loadnpmtasks ('grunt-contrib-Watch'); // default task grunt. registertask ('default', ['clean', 'concat', 'uglify ', 'cssmin']); // grunt. registertask ('default', ['jshint', 'qunit', 'clean', 'concat', 'uglify ']);};
7. Go to practice
It took a little time to configure imweb_proj, and now it has finally reached the actual operation stage. Assume that we are currently in the imweb_proj directory, and imweb_template is the only content in the imweb_proj directory.
Drwxr-XR-x @ 8 casperchen staff 272 5 10 imweb_template
For the operation procedure, see ** jquery plugin example: how to create a project and run a grunt task using an existing template **. Run the following command directly:
Grunt-init -- force imweb_template/NPM installgrunt
The following figure shows the information output from the console after the grunt command is run.
Running "clean: Files" (clean) taskcleaning "Dist "... okrunning "Concat: js_and_css" (Concat) taskfile "Dist/JS/base. JS "created. file "Dist/JS/main. JS "created. file "Dist/CSS/style.css" created. running "uglify: JS" (uglify) taskfile "Dist/JS/base. min. JS "created. uncompressed size: 96927 bytes. compressed size: 7609 bytes gzipped (34814 bytes minified ). file "Dist/JS/main. min. JS "created. uncompressed size: 926 bytes. compressed size: 93 bytes gzipped (305 bytes minified ). running "cssmin: CSS" (cssmin) taskfile Dist/CSS/style.min.css created. done, without errors.
The content in the helloproj directory has changed. Enjoy yourself!
-RW-r -- 1 root staff 2398 5 10 14:39 gruntfile. JS-RW-r -- 1 root staff 605 5 10 readme. mddrwxr-XR-x 6 root staff 204 5 10 cssdrwxr-XR-x 4 root staff 136 5 10 distdrwxr-XR-x @ 8 casperchen staff 272 5 10 imweb_templatedrwxr-xr-x 10 Root staff 340 5 10 jsdrwxr-XR-x 5 root staff 170 5 9 libsdrwxr-XR-x 10 casperchen staff 340 5 10 node_modules-rw-r -- r -- 1 root staff 458 5 10 package. jsondrwxr-XR-x 4 root staff 136 5 9 srcdrwxr-XR-x 5 root staff 170 5 9 Test
V. Comparison of grunt, ant, and mod
Grunt is introduced at the beginning, and ant and AVEN are briefly described below.
- Ant: Kids shoes that have been developed in Java are generally not unfamiliar and have powerful functions. Compared with grunt, ant is easier to get started and the configuration file is more friendly. It is said that ant is used by Yahoo's front-end team, recommended a good tutorial: http://www.book.36ria.com/ant/index.html#index
- MoD, it is easier to get started (partly because mod integrates many common user tasks, and grunt did the same in the early days, but it was abandoned due to multi-version issues ), I have heard of Yuan Yan's sharing before. I plan to try it out in the project. GitHub address: https://github.com/modulejs/modjs
6. Write at the end
Due to time issues, there is no detailed comparison of grunt, ant, and mod. Here is a todo ~~