[Grunt first play] 30 minutes to learn to use grunt to package front-end code

Source: Internet
Author: User

Preface

With the surge in front-end js, dozens of js files under a project are easy to use.
For a complex single-page application, it is common to have hundreds of files. How should we deal with js files at this time?
What should I do with css files ??
These are all problems we encounter in our actual work. For example, we use zepto, backbone, and underscore in our framework.
It is a headache to merge them into a libs file.

But the appearance of grunt makes these things elegant!
It's a simple one-click package. Nima is not impossible!

Grunt

Is a front-end automation tool, a nodeJs-based command line tool, generally used:
① Compressed file
② Merge files
③ Simple syntax check

I am not quite clear about other usage. Here we will briefly introduce grunt's File compression and merge

Beginner. Please forgive me for the error

Preparation Phase 1. nodeJs Environment

Grunt is based on nodeJs, so you need to install the nodeJS environment first.
Http://www.cnblogs.com/yexiaochai/p/3527418.html

2. Install grunt

With the nodeJs environment, we can start grunt, because we may run the package program in any directory, so we need to install CLI
We recommend that you install CLI globally (the grunt command line interface)

 

Each time grunt is run, it uses node's require to check whether grunt is installed locally. If it finds CLI, it loads the local grunt library.
Then, apply the GruntFile configuration in our project and execute the task.
PS: skip this step. After the installation is complete, go to the next step.

Instance learning: Package zepto

When there are many things, they are all tears. Let's go to the instance first, and talk about other things after the instance ends.
Create a project on disk D (folder is good)
Add two files in the file (Do not ask why, first)

① Package. sjon
"name": "demo""file": "zepto""version": "0.1.0""description": "demo""license": "MIT""devDependencies""grunt": "~0.4.1""grunt-contrib-jshint": "~0.6.3""grunt-contrib-uglify": "~0.2.1""grunt-contrib-requirejs": "~0.4.1""grunt-contrib-copy": "~0.4.1""grunt-contrib-clean": "~0.5.0""grunt-strip": "~0.2.1""dependencies""express": "3.x"
② Gruntfile. js

Run npm install in the grunt directory to download the related files:

 

Then our directory will have something more:

There are a lot more things, so we will use them later. At this time, create a src folder under the Directory and create a zepto.

Then add the following code in Gruntfile (leave it alone and add it again)

module.exports = 'package.json''/*! <%= pkg.file %> <%= grunt.template.today("yyyy-mm-dd") %> */\n''src/<%=pkg.file %>.js''dest/<%= pkg.file %>.min.js'  grunt.loadNpmTasks('grunt-contrib-uglify'  grunt.registerTask('default', ['uglify'

After running the grunt command

 

Well, there is one more file and it is compressed. It's not bad !!! Step 1 ends

Understand Gruntdile and package. json

This file is used to store the dependencies of the npm module (for example, if our package depends on the requireJS plug-in, we need to configure it here)
Then, we will configure some different information, such as the file above, which will be put into the package.
Flexible package configuration will be mentioned later

Gruntfile

This file is especially important. He generally does two things:
① Read package information
② Plug-ins load and register tasks and run tasks (all grunt's external interfaces are written here)

Gruntfile consists of four parts.
① Packaging function
This packaging function has nothing to do, that is, all our code must be put in this function.

module.exports = }

You don't need to know why. Just put the code in.

② Project/task Configuration
In Gruntfile, we usually use the initConfig method to configure dependencies.

pkg: grunt.file.readJSON('package.json')

Then we can use pkg. XXX to access the data in the following area.
It is worth noting that the underscore template engine is used here, so you can write a lot here.

Uglify is a plug-in. We configured the package dependency. At this time, we configured a task for the system.
Uglify:

① Find zepto in src for compression (the specific name is found in package)
② Locate the dest directory, create a new one if not, And then compress the file
③ Add several descriptive languages

This task configuration is actually a method interface call. It is good to follow the specifications and will not be followed for the time being.
Here we only define the relevant parameters, but do not load the actual function, so there will be a sentence immediately after:

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

Used to load related plug-ins

grunt == grunt uglify

So far, we have simply Parsed the entire grunt operation. The following is an example of merging files.

Merge files

"devDependencies""grunt": "~0.4.1""grunt-contrib-jshint": "~0.6.3""grunt-contrib-concat": "~0.3.0""grunt-contrib-uglify": "~0.2.1""grunt-contrib-requirejs": "~0.4.1""grunt-contrib-copy": "~0.4.1""grunt-contrib-clean": "~0.5.0""grunt-strip": "~0.2.1"

Then write the code like this.

module.exports = 'package.json'';''src/zepto.js', 'src/underscore.js', 'src/backbone.js''dest/libs.js''grunt-contrib-concat'  grunt.registerTask('default', ['concat'

After the operation, a magic scene occurred:

The three files are compressed into one, but they are not compressed. Therefore, we will add one more step here to compress the files and then merge them.

module.exports = 'package.json'';''src/zepto.js', 'src/underscore.js', 'src/backbone.js''dest/libs.js''dest/libs.js''dest/libs.min.js''grunt-contrib-uglify''grunt-contrib-concat'  grunt.registerTask('default', ['concat', 'uglify'

My approach here is to merge and form a libs, and then compress the libs into libs. min. js.

So let's change the practice here, first compress and then merge. In fact, unglify has already done these things.

module.exports = 'package.json'"my_target""files"'dest/libs.min.js': ['src/zepto.js', 'src/underscore.js', 'src/backbone.js''grunt-contrib-uglify'  grunt.registerTask('default', ['uglify'

So we will not pay attention to concat for the moment.

Finally, it's not too early today. We finally studied grunt and require, so we will end our study today.

Merge files managed by requireJS

With the above foundation, we have to compress all the js files managed by require and merge them into one file.
First, we create a simple program that uses zepto, backbone, and underscore (in fact, I didn't use anything)

'''zepto''_''_''$''Backbone''$': 'src/zepto''_': 'src/underscore''B': 'src/backbone''B'], 

In this case, several files will be automatically loaded. How can we merge them into a libs. js ???

We use the custom task method here, because we do not seem to have introduced him

Plug-ins required for using requireJS

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

In this way, our package. json has no practical significance:

"name": "demo""version": "0.1.0""description": "demo""license": "MIT""devDependencies""grunt": "~0.4.1""grunt-contrib-jshint": "~0.6.3""grunt-contrib-concat": "~0.3.0""grunt-contrib-uglify": "~0.2.1""grunt-contrib-requirejs": "~0.4.1""grunt-contrib-copy": "~0.4.1""grunt-contrib-clean": "~0.5.0""grunt-strip": "~0.2.1""dependencies""express": "3.x"

The grunt configuration file for require is as follows (gruntCfg. json ):

"requirejs""main""options""baseUrl": """paths""$": "src/zepto""_": "src/underscore""B": "src/backbone""Test": "src/Test""web""include""$""_""B""Test""out": "dest/libs.js"

Here we need to package these files into the dest libs. js file. This file will be taken as needed. The core code is as follows:

module.exports = 'grunt-contrib-requirejs'  grunt.registerTask('build', 'require demo',      tasks = ['requirejs'     srcDir = 'src'     destDir = 'dest'    grunt.config.set('config'     taskCfg = grunt.file.readJSON('gruntCfg.json' options ==== pos = -1 requireTask ===="requirejs"

After running the job, you should: grunt build

 

At last, I found that ye xiaochai had three words, so I was relieved and safe !!!!!!

Next Episode Preview 1 HTML file packaging 2 Style File packaging 3 mobile package file

Our development version and use version may not be in the same place.

4 branch processing

Package different branches

5 native package and HTML5 package

In the era when HTML5 is embedded into webview, we certainly have a packaging that requires both website files and app files.

Package Channels

Of course, the package of sub-channels and sub-branches may exist.

Till now, To be continued ......

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.