"Front-end benefits" build an automated web front-end development environment with grunt-a complete tutorial

Source: Internet
Author: User

jquery in the use of grunt,bootstrap in the use of grunt, Baidu Ueditor in the use of grunt, you have no reason not to learn, do not!

1. Preface

Everyone web front-end developers, if you do not know grunt or heard, but not skilled use of grunt, then you really really really out (three "true" repetition, to show the focus). As for the role of grunt, here is not detailed, in short, if you do Web front-end development, you must use grunt. Also, it is completely free and not pirated. Why not use something that is both powerful and free?

Of course, if you can find a better alternative to Grunt's other tools are also possible, such as gulp. Gulp future may replace grunt, but now the market share is still inferior to grunt. And this tool we need to use now, all do not hesitate, take doctrine, first with grunt, that is, learn to use.

This article is intended to explain the introduction of grunt and the use of several plug-ins that are most commonly used in grunt. The length may be longer, and we will look patiently. This article provides a detailed and clear explanation of every point of knowledge. But--if you don't finish this article, I have one last big trick. But you may have to pay for a meal + a pack of cigarettes--check out my recorded video tutorial, "Building an automated web front-end development environment with Grunt" (the tutorial has a source download) to make sure you'll use it when you're finished.

(PS: It happens that this article is written based on the Windows environment, and the video tutorial is based on Mac OS recording, both of them)

Not much nonsense, video tutorial You also don't look, money don't worry about flowers. First challenge your understanding ability, see below to tell whether clear, can understand.

2. Installing Nodejs

Grunt and all grunt plugins are based on Nodejs, and if you don't have Nodejs on your computer, install them. Installation Nodejs is very simple, complete fool type, next step Next, the installation method, here no longer repeat. Go to https://nodejs.org/, click on the page of the green, big "install" button.

After you have installed Nodejs, you can enter "Node-v" in your console to view the Nodejs version and, by the way, Nodejs whether the installation was successful.

  

Note two points. First, Grunt relies on Nodejs's v0.8.0 and above; second, the version of the odd version is considered to be an unstable development version, but the download from the official website should be a stable version of even numbers.

3. Installing GRUNT-CLI

Note that if your computer is not networked, the following actions you can not do, so, first of all to ensure that computer networking.

"CLI" is translated to "command line". To use grunt, you must first install GRUNT-CLI into a global environment and use the Nodejs "NPM install ..." To install it. If you don't know how Nodejs NPM installs the software, don't ask first, just do as I say.

Open the console ( Note:underwindows System, open with Administrator privileges ), enter:

  

Note that the Mac OS system, and some Linux systems, precede this sentence with "sudo " instructions.

  

Enter, the command line appears a rotating dash, indicating that the network is loading. Load time to see how fast you speed, but this software is smaller, the general load time will not be very long, a little while, the load is finished. You will see the following interface.

  

To verify that the GRUNT-CLI is installed and in effect, you just need to continue typing the "grunt" command on the command line. If effective, the following results appear:

  

You do not care what these results mean, in short, these hints appear to prove that your GRUNT-CLI installation is successful.

4. Create a simple website

Grunt is applied to the actual project, so we have to have a simple test site to demonstrate the installation and use of grunt.

First of all, I built a "grunt_test" folder under the computer's D-disk, which built three empty folders, two blank documents, such as the name. (Note that the first letter of the Gruntfile.js file is capitalized!) )

  

The other things do not control first, the Package.json this file to write some things. Remember, since the file suffix is called "json," the format of the file must be a strict JSON format. What, not familiar with JSON? As a web front-end Program ape, JSON is an essential lesson. There is a tutorial, "Json2.js source Interpretation," that will give you a thorough understanding of JSON.

The book belongs to the story. Package.json content We write in the following format:

  

Quite simply, we have written the name and version of this website or system. However, not only to write in the empty space, will be used in the future, how to use, we will introduce the following, do not worry.

And what does the last "devdependencies" mean? The literal interpretation is "development dependency", that is, what tools we will rely on to develop this system now. Now the code line is not written, depends on who? No one depends on it! So, write an empty object first. But the following will slowly fill it up.

In addition, you can add any JSON-formatted code in Package.json, which is inherently free and only limited by the JSON code format.

How, see here, do not feel the following is very suspense, very want to see it? Then go on!

5. Installing grunt

The protagonist is always belated. "Kingdoms" in the opening three minutes after the first to come out Zhuge Liang, "Outlaws of the Marsh" in the 18th back only to please the song Jiang. And the protagonist of our article, also come out not early.

Next we will have a series of plug-ins installed, their installation process and grunt the same. But their execution is based on grunt, so grunt can be called a "build tool". Grunt does not have a specific role, but it can combine a single plug-in that has a specific effect, forming a holistic effect.

For example, you need to check the JS syntax error and then compress the JS code. If you take these two steps manually, it will cost a lot of money. Grunt will save you the cost of these manual operations.

The book belongs to the story. Note that installing grunt here is no longer a global installation and requires you to enter the specific directory of the website or system in the console. Here we go into the D:\grunt_test directory. Then enter the following command.

  

Note, do not press ENTER first, do not execute, first look at the description below!

What needs to be explained here is that "-save-dev" means to save grunt as a development dependency for this directory while installing grunt in the current directory. See "Development dependencies" this time, do you feel a little familiar? The development dependencies are stored in "devdependencies" when you configure Package.json.

What is the effect of saving a specific development dependency? Just install it. First, "Devdependencies" in Package.json corresponds to an empty object before running the command to install grunt.

Now let's run this line of command. You'll see a few warning tips, no need to worry about it. Then the next step is the load state, a rotating small horizontal line. Wait a little while and you will be prompted to install successfully. Such as:

  

Now you should open the Package.json to see what the "Devdependencies" has changed. I change here like, see if you are the same as mine?

  

And then you look at the files in the document directory or the folder changes? I've got an extra "node_modules" folder with a "grunt" folder with several documents in it. This is where the grunt source files are stored.

  

This is the time to witness miracles, don't worry, miracles are not over yet. Then you run the "grunt" command on the console. If you get a warning hint, that means grunt has worked. Such as:

  

After the above three steps, the grunt has been successfully installed in this directory.

Why, then, do we have a warning hint when we have just executed the grunt? According to the tip, the information we learned is: Task "default" not found, how to solve this problem? --Of course, keep looking down.

6. Configure Gruntfile.js

As the name implies, gruntfile.js this file, it must be for grunt to do some kind of configuration. According to Grunt, we first configure the gruntfile.js as the following format.

  

In the above code, we see the word "default" in the warning hint that just ran the grunt command. We may as well run the grunt command at this time to see if the words "warning" and "default" will appear again.

  

The result of the operation tells us "done, without errors". Then go on.

  

Also note the gruntfile.js in the sentence:

  

This sentence is in the gruntfile.js to get the contents of the Package.json. When we configured Package.json above we said: The contents of Package.json are not only used to occupy the position, but also can be obtained from other places. Didn't you get the Package.json content here? As for how to use, the following will be introduced, or continue to look down.

7. Grunt Plugin Introduction

Enter the plugin list page of Grunt official website Http://www.gruntjs.net/plugins, we can see Grunt to the current location of all plugins. Now there are 4,560 plugins, and this number is increasing every day. And, since they appear on the official website, they must have been audited.

Plug-ins fall into two categories. The first is the plug-in that the Grunt team contributed, preceded by the "contrib-" prefix, and marked with an asterisk in the plug-in list. The second category is a third-party plug-in that does not have these two characteristics.

Like jquery, the plug-ins are so many that they're definitely not all used. Grunt website plug-in list of the first few plugins in the first few plug-ins, download the most, they are definitely everyone in use plug-in. The first Jshint plug-in downloaded nearly 890,000 times in the last 30 days, which is how amazing the download volume!

Let's briefly describe the functions of the previous plugins and see if you need them in the actual coding process. In fact, you do not need to see the answer--certainly needs--otherwise, how can the download amount so high?

    • Contrib-jshint--javascript syntax error checking;
    • contrib-watch--real-time monitoring file changes, call the corresponding task re-execution;
    • contrib-clean--empty files and folders;
    • contrib-uglify--compressing JavaScript code
    • contrib-copy--Copying files, folders
    • contrib-concat--merging multiple files into a single file
    • karma--front-end automated testing tools

The above plugins, this article will not be all mentioned. But as part of the explanation, I think you can master the method of using the grunt plugin. Know the way, then you can refer to the official documentation to use the plugin you want.

Grunt integrates the wisdom of Web front-end development around the world, more powerful than you think, and its plug-in library can handle everything you encounter in Web front-end development.

What are you waiting for, keep looking down.

8. Using the Uglify plugin (compressed JavaScript code)

The function of the Uglify plugin is to compress JavaScript code. As for the need and meaning of JavaScript code compression, don't you have to repeat it here? Almost every JavaScript class library or framework has a **.min.js compressed version.

Q. What tools do you use to compress code when you do JavaScript development? I think there will be a lot of answers to this question. However, using the grunt Uglify plugin for compression, the effect is absolutely not lost to any plug-in.

To install a plugin, you first have to go to the documentation page of this plugin on the grunt website. We found "contrib-uglify" click to enter in the Grunt website plugin list page. You need to see the instructions, and then follow the instructions to install them. Here we only focus.

Install the Uglify plugin in the same way that you install grunt. Do you remember how the grunt was installed?

  

Here again the familiar "-save-dev", the specific role in the above installation grunt has already said, no longer repeat. Run this command. After the installation is complete, you will see the changes in the "devdependencies" node in Package.json and the changes in the "Node_modules" folder. These two points have been said in detail when installing grunt.

It is not yet available and needs to be configured in Gruntfile.js.

But let's not worry about it. Since we want to use Uglify to compress JavaScript code, of course we have to create a JS file to do the experiment. We create a new "Test.js" in the existing "src" folder and write some code casually. Obviously, we can't write the compressed code through both hands and the keyboard.

  

The test file is set up. We are going to compress this JS file next.

Of course, who to compress? Where to compress? These need to be configured in Gruntfile.js. is divided into three steps:

The first step is to configure the configuration parameters of the uglify in the Grunt.initconfig method. Such as:

  

, there are two configurations for uglify.

The "Options" rule allows the resulting compressed file to be taken with banner, that is, the first line of the generated compressed file is added with a sentence description. Note that the contents of the Package.json are used to obtain the pkg.

The source and destination files are configured in "Build". That is, who is required to compress? Who will be generated after compression? Note that we will name the file name of the target files through the name and version of the Pkg.

(PS: The contents of the Package.json mentioned above have finally found the place where he was applied.) The benefits are: for example, the management of the file version, you only need to modify in Package.json, Grunt will automatically generate the corresponding version of the file according to the latest version number. You do not have to manually modify the file name. )

Finally, here is only the "options" and "Build" basic applications, there are many ways to use, you can go to the official website.

In the second step, after the Grunt.initconfig method, let grunt load the plugin. Light configuration, not loading on, how to use AH?

  

The third step, when the grunt command executes, do you want to execute the uglify plugin immediately? If you want, just write it or don't write it. I'm in need now, so I'm writing. There may also be no need, in this case who knows?

  

The above three steps are OK, let's try it out next. Run the grunt command in the console to see what the results are.

The console will enter the following information:

  

To see if you have generated a compressed JS file?

  

Sure enough The file name is generated based on name and version in Package.json. Furthermore, the banner of the compressed code is also in compliance with the configuration requirements in Gruntfile.js.

The above is the Uglify plug-in detailed installation, configuration instructions. JavaScript uses uglify compression, and CSS can be compressed using the Cssmin plugin. Install, configure the same method, no longer repeat.

9. Using the Jshint plugin (check for JavaScript syntax errors)

If you just write a dozens of line JS code to do a small test, syntax error checking is not necessary. But I believe that the friends who read this article, certainly not limited to this, you may need to write a lot of JS code every day to complete their work. Even a bull and a careful person would make some low-level mistakes, but Jshint would not. Therefore, your best practice is to let jshint to help you check the JS code you just wrote, with errors immediately found immediately processing. In this way, you do not need to meet every few days in the conference room for manual Code walk. Timely code walk, you do not have to deliberately pay attention to grammatical errors.

There are some JS beginner's friends, or have had many years of JS experience, but "do not think enterprising" friend. You may not even know some of the JS grammar methods. For example, you probably don't know what the difference is between "= =" and "= = =", and you don't know the downside of defining variables within a block of statements, and there's more to it than you know. What to do? Let Jshint help you.

Next, we describe the installation and configuration of Jshint.

Plug-in installation and installation grunt, uglify no difference, here no longer repeat. Execute the following command directly

  

Configure Jshint and configure uglify as well. We talked about three steps when we configured Uglify, which is also a three-step process.

The first step is to configure Jshint in the Grunt.initconfig method.

  

As with the uglify configuration, it is divided into "options" and "build" two parts. The syntax for jshint to check which JS documents is described in "build". The "Options" section describes how the rules are checked for syntax, and the descriptions of these rules are stored in a file called ". Jshintrc" in the root directory of the Web site. So we add this document below the root of the website and fill in the contents of the file.

  

The format of the code in the. jshintrc file is also subject to strict JSON syntax, otherwise it is not valid. What do these configurations mean? Want to learn more about Baidu can go to search "jshint configuration " keyword, you can know the answer. There is too much space here, but more introduction. Anyway, this. Jshint is my usual configuration.

The second step is to load the plugin. Same as the Uglify loading method. Note that there is no sequencing here.

  

The third step is to configure the grunt command to perform the task when it starts, here note the sequencing. Do you want to check the grammar first? Or merge it first? --wise people should know that it is better to check the grammar first, because the grammatical pairs, what is the meaning of merging?

  

After the three-step configuration is over, we can test how this jshint is used. Here I deliberately write a syntax error for the currently created Test.js file.

  

Then we execute the "grunt" command, see if Jshint can identify these two errors for us? The results are as follows:

  

See no, Jshint very clear the identification of these two errors. and notice that no, after the Jshint error, the uglify behind it will not continue to execute. This formally we want the result.

We modify these errors, execute the grunt command here, the result is not prompt error, and both Jshint and uglify are executed smoothly.

10. Using the Csslint plugin (check for CSS syntax errors)

Check the CSS file syntax error to use the Csslint plug-in, its installation configuration method and Jshint almost identical. But Csslint relies on a file called ". Csslintrc" as the rule for grammar testing, my ". Csslintrc" file is as follows. We will not repeat the rest of the content.

  

11. Using the Watch plugin (truly automated)

You can always have a question, the above will be the plug-in, every time the plug-in function, you have to execute the "grunt" command, such a cumbersome operation, said the " Automation " it? Don't worry, it's a matter of solving this problem by using the watch plugin.

First install the watch plug-in, if the installation no longer repeat. Next to configure the watch plugin, the configuration is divided into three steps, no longer described in detail, only map description.

The first step. Configuring watch will monitor which files are changed and, if so, what plug-in functions to execute immediately if these files change. For example, watch will monitor changes to all JS files and CSS files under the SRC folder, and immediately execute the Jshint and uglify two plugin functions once the changes are in place.

  

The second step, direct mapping

  

The third step, direct mapping

  

These three steps are finished, that is, watch plug-in configuration is complete. Run the grunt command and the console prompts watch to start listening. To stop at this point, press CTRL + C.

  

Now that we're listening, we'll try to see if the monitor is effective. We'll remove a semicolon from the Test.js code to see if it can automatically check out the error.

  

The results show that watch checks for changes to the Test.js file and prompts for syntax errors by executing jshint. More importantly, it's still listening, not stopping. Indicates that it is waiting for you to modify the error and re-listen for the check. Then let's not disappoint it and fix the grammatical mistakes. See how it will be handled.

  

It also detects the file changes, this time the syntax is not wrong, it smoothly executed the jshint and uglify, after the completion of the monitoring again. How obedient the tool!

Well, your question has been answered-- automation .

12. The so-called "build" above

When you describe the configuration of each plug-in above, the name "build" is used as a configuration item.

  

So does this have to be a "build" name? The answer is obvious, of course not. I did not directly said before, because I have to first put the installation and configuration of the plug-in to understand, not change the transfer too much knowledge, and now we have to say.

You can use any string instead of "build" (but conform to the JS syntax rule). You can even write the content that "build" points to separately. This is friendly to multi-person collaborative development. The good design is this: Let the user play their freedom to the director, not to limit them.

  

For example, I have made a change to the configuration of Jshint, you can modify it yourself, and then execute the grunt command to try it. The command line has the word "test1" and "test2".

13. Batch Install Plugin

Please crossing continue to follow me to think, learn without thinking is not a problem.

So far, I've just installed 3 plugins, and the "Node_modules" folder occupies 18MB of space. Everyone guess, I upload code to the development of the library, will not be "node_modules" content also upload it? Since I have asked, the answer must not be uploaded.

The question comes again, if I as a development environment of the building, I do not put "node_modules" upload, other developers together, how to get these grunt plug-ins and tools? Someone answered to let them go manually one installation at a time--first This is a stupid method, second if I installed the old version, and they are now installed on their own may be the new version. New and old may not be compatible AH.

What should I do?

In fact, the answer is very simple-when I upload the source code, will certainly put Package.json upload, and Package.json in the "Devdependencies" recorded the development of the system dependencies, and then I through the Nodejs NPM can be installed in batches.

Do an experiment. I create a new directory "Grunt_test_1" under D, and then copy the Package.json in "Grunt_test". In the open command line jump to "grunt_test_1", execute "npm install" command, see what results.

  

At this point, press ENTER to execute the command, the result of "grunt_test_1" generated the "Node_modules" folder, which installed the Package.json "devdependencies" configuration plug-in. Also, the version is always on.

It's amazing!

  

14. System File Structure

When using grunt to build a web front-end development environment, the document directory may not be the same as before. Because you manually write the code file, it is definitely not your final output file. These also need to undergo grunt various plug-ins inspection, merger, compression to the final output to the user.

Here I take an example of the document structure of my own open source project Wangeditor .

  

, the "src" folder is stored in the original code file, "dist" folder is stored in the final generated code files, "demo" is stored in a number of test pages.

Of course, the file organization of each system is not the same, but I suggest you follow such a thought to organize the document structure. You can also go to GitHub to refer to the document structure of the famous open source projects of jquery and Bootstrap. Look at the jquery output although it is a simple JS file, but its development environment is how complex.

It's not easy to do the front end.

15. End

This article I wrote in Word, and then pasted into the blog Park published. So far, I have written a total of 20 pages, 6,700 words, all hand-written, manual. Write a blog to write this part, I also sort of spell!

  

If you read this article will not grunt, or you do not bother to read the article, too tired, I suggest you go to see my record, "using grunt to build a fully automated web front-end development environment" This video tutorial, the video is definitely more detailed, and can download the source code.

Finally, if you feel that this article is helpful to you, you can order a praise!

"Front-end benefits" build an automated web front-end development environment with grunt-a complete tutorial

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.