1. Introduction

The purpose of this article is to get started with Grunt and explain the use of some of the most common Grunt plug-ins

2. Installation node. Js

Grunt and all Grunt plugins run on NodeJS. If you don’t have NodeJS on your computer, go ahead and install it. Installing NodeJS is very easy, a completely foolproof, next step, next step, which I won’t go into here. Go to https://nodejs.org/ and click the big green “Install” button on the page. I here in baidu cloud disk deposit one, the need to click download

After installing NodeJS, you can type “node-v” into your console to see the version of NodeJS, and also to test whether the installation was successful.

As shown in the figure:

It is important to note that Grunt relies on NodeJS versions V0.8.0 and up.

3. The installation of grunt – CLI

Note that you can’t do any of the following if your computer is not connected to the Internet, so first make sure your computer is connected to the Internet.

“CLI” is translated as “command line”. To use Grunt, you must first install Grunt-CLI into the global environment by using nodejs’ “NPM install…” To install. If you don’t know how to install NodeJS NPM, don’t ask, just follow my instructions. Open the console (note: under Windows, please open it with administrator privileges), and enter:

 

Note that on Mac OS and some Linux systems, you add "sudo" before the sentence.

Enter, the command line will appear a small rotating bar, indicating that the network is loading. Loading time depends on the speed of your network, but this software is relatively small, the general loading time will not be very long, after a while, the load finished. You should see the following screen.

To verify that the GRUNT-CLI installation is complete and working, simply type “grunt” on the command line. If valid, the following results will occur:

4. Create a simple website

Grunt is intended for real projects, so we need to have a simple test site that demonstrates how to install and use Grunt.

First, I created a “grunt_test” folder under the computer’s E drive with three empty folders and two empty documents, as shown in the image below. (Note the capitalization of the gruntfile.js file!)



Forget about everything else, just write something about package.json. Remember, since the file suffix is called “JSON,” the format in the file is strictly JSON.

The book goes back to business. The content of package. json is written in the following format:

{" name ":" grunt_test ", "version" : "1.0.0", "devDependencies" : {}}

Very simple, we put the name of the website or system, version of the written. However, it is not only written here to occupy space, will be used in the future, specific how to use, we will be introduced in the following, don’t worry.

And what does that last “devDependencies” mean? The literal definition is “develop dependencies,” which tools our current system will rely on to develop. Now I’m not writing a line of code, so who does that depend on? Who does not depend on! So, just write an empty object first. But I’ll fill it in later on.

In addition, you can add any code in package.json that conforms to the JSON format. It is born free and is limited only by the JSON code format.

How, see here, do you think the following is very suspense, very want to see it? Then go ahead!

5. Installation of grunt

We are going to have a series of plugins installed in the same way as Grunt. But their implementation is based on Grunt, which is why it’s called a “build tool.” Grunt has no specific role, but it can be used to combine plug-ins that have specific roles to create an overall effect.

For example, you need to check for JS syntax errors before compressing the JS code. If you do both manually, it will cost you a lot. Grunt can save you the cost of these manual operations.

The book goes back to business. Note that installing Grunt here is no longer a global installation and requires you to go to the site or system directory from the console. Here we enter the E:grunt_test directory.



Then type the following command:



Note, do not press enter, do not execute, first look at the following description!

It is important to explain that “– save-dev” means to save Grunt as a development dependency of the current directory at the same time that it is installed. Looking at “developing dependencies” this time, does that sound familiar? When configuring package.json above, the development dependencies are stored in “devDependencies”.

What is the effect of saving specifically as a development dependency? Just install it. First, before running the command to install Grunt, the “devDependencies” in package.json corresponds to an empty object.

Now let’s run the command line. You’ll see several warnings, but don’t worry about them. And then there’s the loading state, a little rotated bar. Wait for a while and you will be informed that the installation was successful. The diagram below:



Now you should immediately open package.json to see what happens to “devDependencies” there. My changes here are as follows. Is yours the same as mine?

{" name ":" grunt_test ", "version" : "1.0.0", "devDependencies" : {" grunt ":" ^ 0.4.5 "}}

Then you can see what happened to the files or folders in the document directory. Here I have a “node_modules” folder with a “grunt” folder and a few files in it. This is where the Grunt source files are stored.



This is a time for miracles. Don’t worry. The miracles are not over yet. Then you run the “grunt” command from the console. If you get a warning, Grunt is working. The diagram below:

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

So, why did we have a Warning when we just executed Grunt? Task “Default” is not found. Task “Default” is not found. — Keep reading, of course.

6. Configuration Gruntfile. Js

As the name implies, the gruntfile.js file must be used to do some configuration for grunt. According to Grunt, we will start by configuring gruntfile.js to the following format.

// Package module.exports = function(grunt){// Exports = function(grunt){ grunt.file.readJSON('package.json') }); Grunt.registerTask ('default',[]); grunt.registerTask('default',[]); };

In the above code, we see the word “default” in the warning prompt when we ran the grunt command. Let’s run the grunt command again at this point to see if the words “warning”, “default” and so on appear again.



The result tells us “Done, without errors”. Let’s keep going.

Also note the sentence in gruntfile.js:

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

Get the contents of package.json in gruntfile.js. As we said when configuring package.json above, content in package.json is not only used for location, but can also be obtained elsewhere. Don’t you already get the package.json content here? As for how to use the acquisition, the following will be introduced, or continue to read below.

7. Introduction to Grunt Plug-in

Enter the grunt plugin list page the club’s official website http://www.gruntjs.net/plugins, we can see grunt so far all the plug-ins. Plug-ins fall into two categories. The first category is the plug-ins contributed by the Grunt team, whose names are prefixed with “contrib-” and are marked with an asterisk in the list of plug-ins. The second category is third-party plugins that do not have either of these characteristics.

As with jQuery, there are so many plug-ins that you can’t use them all. The first few of the plugins on the Grunt website are the most downloaded, and they are definitely the ones that everyone is using.

Let’s briefly describe what the first few plug-ins do and see if you need them in your actual coding. You don’t have to look at it to know the answer — you definitely need to — otherwise why would you get so many downloads?

  • Contrib-jshint — JavaScript syntax error check;
  • Contrib-watch — monitor file changes in real time, call the corresponding task to re-execute;
  • Contrib-clean — Clears files, folders;
  • Contrib-uglify — Compress JavaScript code
  • Contrib-copy — Copy files, folders, etc
  • Contrib-concat — Merges the code of multiple files into a single file
  • Karma – front-end automated test tool

This article will not cover all of these plug-ins. But as you go through some of them, I think you’ll get a handle on how to use the Grunt plugin. Knowing the method, you can then refer to the official documentation to use the plug-in you want.

Grunt is more powerful than you might think, and it has a library of plugins for almost anything you might encounter in web front-end development. What are you waiting for? Keep reading.

8. Use the Uglify plugin (compressing JavaScript code)

The Uglify plug-in compresses JavaScript code. As for the necessity and significance of JavaScript code compression, there is no need to repeat it here, right? Almost every JavaScript library or framework has a compressed version of **.min.js.

By the way, what tools do you use to compress code when you do JavaScript development? I think there are many answers to this question. However, using Grunt’s uglify plugin for compression is as good as any plugin.

To install a plugin, you must first go to the plugin documentation page on the Grunt website. In the plugin list page of Grunt official website, find “contrib-uglify” and click to enter. You have to read the instructions here and then follow them for installation. We’ll stick to the main points here.

You install the Uglify plugin in the same way you install Grunt. Remember how Grunt was installed?

npm install grunt-contrib-uglify --save-dev

Here again comes the familiar “– save-dev”, which has been explained in the previous section of the Grunt installation. Run this command. After the installation is complete, you should see the changes in the “devDependencies” node in package.json and the changes in the “node_modules” folder. Both of these points were discussed in detail when Grunt was installed.

It is not available yet, but needs to be configured in gruntfile.js.

But don’t worry. Since we’re going to use Uglify to compress JavaScript code, of course we’ll have to create a JS file to experiment with. Let’s create a new “test.js” in the existing “SRC” folder and write some random code. Obviously, you can’t write compressed code with your hands and keyboard.

(function(window,undefined){ function add(a,b){ return a + b; } the add (10100); })(window);

The test file is set up. The next step is to compress the JS file.

Of course, who’s going to be compressed? Where is it going to compress? These all need to be configured, and are configured in gruntfile.js. It is divided into three steps:

The first step is to configure the configuration parameters for Uglify in the grunt.initConfig method. As follows:



The configuration code for uglify:

Uglify :{options:{banner:'/*! <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %> */' }, build:{ src:'src/test.js', dest:'build/<%=pkg.name%><%pkg.version%>.min.js' } }

In the figure above, the configuration for Uglify has two items.

“Options” allows the generated zip file to have banners, which means adding a sentence to the first line of the generated zip file. Notice the use of PKG to get the contents of package.json.

The source and target files are configured in “build”. Which specifies who to compress? Who will be generated after compression? Note that we name the file name of the target file with PKG name and version.

(PS: The package.json content has finally found its place. The advantage of this is that, for example, you only need to modify the file version in package.json and Grunt will automatically generate the corresponding version of the file based on the latest version number. You don’t have to change the file name manually.

Finally, this is just the basic use of “options” and “build”, there are many other ways to use it, you can go to the website.

Second, after the grunt.initConfig method, ask Grunt to load the plug-in. Light configuration, do not load, how to use ah?



The code is as follows:

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

Third, when the grunt command is executed, do you want to immediately execute the uglify plug-in? If you do, write, otherwise don’t write. I need it now, so I’ll write it. Or maybe not, in which case who knows?



The code is as follows:

grunt.registerTask('default', ['uglify']);

The above three steps have been OK, let’s go to try. Run the grunt command in the console and see what happens.

The console will enter the following information:



Let’s see, did we generate a compressed JS file?



Indeed as expected. The file name is generated from the name and version in package.json. Moreover, the banner of the compressed code also conforms to the configuration requirements in gruntfile.js.

The above is the detailed installation and configuration instructions of Uglify plug-in. JavaScript is compressed using Uglify, and CSS can be compressed using the CSSMin plugin. Installation, configuration methods are the same, no more details.

9. Use the jshint plugin (check for JavaScript syntax errors)

If you just write a few dozen lines of JS code to do a little test, you don’t need to check for syntax errors. But I believe that reading this article friends, certainly not limited to this, you probably need to write a lot of JS code every day to complete their work. Even the most intelligent and careful people can make some elementary mistakes, but JSHINT does not. Therefore, your best practice is to ask JSHINT to help you check the JS code you have just written every moment, and deal with any errors immediately. This way, you don’t have to get together in the conference room every few days to do manual code walkthroughs. In a code walkthrough, you don’t have to pay attention to syntax errors.

There are some JS primary entry of friends, or has many years of JS experience, but “not ambitious” friends. You may not know some JS syntax methods by now. For example, you may not yet know the difference between “==” and “===”, you may not yet know the disadvantages of defining variables within a block of statements, and there is much more you do not know. How to do? Let jshint help you.

Next, look at the installation and configuration of JSHint.

Installing a plug-in is no different than installing Grunt or Uglify, so I won’t go into details here. Execute the following command directly

npm install grunt-contrib-jshint --save-dev

Configuring jshint is the same as configuring uglify. We covered three steps in configuring uglify, and there are three steps here.

The first step is to configure JSHint in the grunt.initConfig method.



The code is as follows:

Jshint :{build:[' gruntfile.js ',' SRC /*.js'], options:{jshintrc:'.jshintrc' '// Detect js code errors according to the file's setup specification. You can modify the rules by yourself}}

Like the Uglify configuration, it is divided into “options” and “build” sections. “Build” describes the syntax of which JSHINT JS documents to check. The “options” section describes which rules to check the syntax with, and the description file for these rules is stored in a file called “.jshintrc “at the root of the site. So we added this document under the root of the site and filled in the contents of the file.



The code is as follows:

{
  "curly": true,
  "eqeqeq": true,
  "immed": true,
  "newcap": true,
  "noarg": true,
  "undef": true,
  "boss": false,
  "eqnull": true,
  "node": true,
  "expr":true,
  "noempty":true,
  "regexp":true,
  "browser":true,
  "devel":true
}

The format of the code in the.jshintrc file should also follow the strict JSON syntax, otherwise it will be invalid. So what do these configurations mean? Want to know more about can go to Baidu search “JSHINT configuration” keyword, you can know the answer. Here because the space is too much, but more introduction. Anyway, this dot jshint is my usual configuration.

Second, load the plug-in. It’s the same loading method as uglify. Notice, there’s no order here.



The code is as follows:

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

The third step is to configure the tasks to be performed when the grunt command is started, in order of importance. Do you want to check your grammar first? Or should we merge first? — Smart people should know that it is better to check the grammar first, because the grammar is right, what is the point of combining?



The code is as follows:

grunt.registerTask('default', ['jshint','uglify']);

After the above three steps have been configured, we can test how the jshint works. Here I deliberately wrote a syntax error in the currently created test.js file.



Then we execute the “grunt” command to see if jshint can identify the two errors for us. The results are as follows:



See, JSHint clearly recognizes these two errors. And did you notice that uglify didn’t continue after the jshint error? That’s exactly what we want.

We fixed these errors and executed the grunt command here. There were no errors and both jshint and uglify were executed smoothly.

10. Use the CSSLint plugin (check for CSS syntax errors)

To check for syntax errors in CSS files, use the CSSLint plugin, which is installed and configured almost exactly the same way as JSHint. It’s just that CSSLint relies on a code called”.csslintrc“As a rule of grammar check, my”.csslintrcThe document is as follows. We won’t go into the rest here.

The code is as follows:

{
  "adjoining-classes": false,
  "box-sizing": false,
  "box-model": false,
  "compatible-vendor-prefixes": false,
  "floats": false,
  "font-sizes": false,
  "gradients": false,
  "important": false,
  "known-properties": false,
  "outline-none": false,
  "qualified-headings": false,
  "regex-selectors": false,
  "shorthand": false,
  "text-indent": false,
  "unique-headings": false,
  "universal-selector": false,
  "unqualified-attributes": false
}

11. Use the Watch plugin (true automation)

You can always wonder that the above plugin has to execute the “grunt” command every time the plugin function is executed. This operation is very tedious. Don’t worry, let’s fix the problem — with the Watch plugin.

First, install the Watch plug-in, if the installation is more detailed. The next step is to configure the Watch plugin. The configuration is divided into three steps.

The first step. Configuring Watch monitors which files change and which plug-in functions to perform immediately if those files change. As shown in the figure below, watch will monitor the changes of all JS files and CSS files in the SRC folder, and execute them immediately once the changes are madejshintanduglifyTwo plug-in features.

The second step, directly post the code:

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

Step 3: Post the code directly:

grunt.registerTask('default', ['jshint','uglify','watch']);

These three steps are completed, that is, the configuration of the Watch plug-in is completed. Run the grunt command, and the console tells you that watch has started listening. To stop, press Ctrl + C.

Since we’re listening, let’s try to see if the listening is working. Let’s remove a semicolon from the test.js code to see if it automatically detects the error.

The results show that the watch is checking for changes in the test.js file, and that it is showing syntax errors by executing jshint. More importantly, it is still listening, not stopping. It means it is waiting for you to fix the error and listen again. Then let’s live up to it and fix the grammar error. Let’s see what it does.



It detected file changes again, and this time there were no syntax errors. It executed jshint and uglify smoothly, and then listened again after the execution. What an obedient tool!

Well, that’s answered your question — automation.

12. The so-called “build” above

The name “build” is used as a configuration item for each plug-in configuration described above.

Does it have to be called “build”? The obvious answer is, of course not. The reason I didn’t say this directly is because I wanted to explain the installation and configuration of the plug-in first, so I don’t want to transfer too much knowledge at once, but I’m going to tell you all about it now.

You can use any string instead of “build” here (as long as it conforms to JS syntax rules). Even more, you can separate out what “build” points to. This is friendly for collaborative development. Good design is about letting users do what they want, not limiting them.



As shown in the image above, I have made some changes to the jshint configuration. You can modify it yourself, and then execute the grunt command. The command line will have the words “test1” and “test2”.

As shown in the figure:

13. Batch install plug-ins

Please continue to follow me to think, learning without thinking is useless.

So far, I’ve only installed three plug-ins, and the “node_modules” folder takes up 18MB of space. Can you guess if I also upload the contents of “node_modules” when I upload the code to the development library? Since I asked, the answer must be no.

If I don’t upload “node_modules” as an environment builder, how can other developers get these Grunt plugins and tools? Someone told them to manually install them one by one – first of all it’s a stupid way to do it, and second of all if I installed the old version and they installed the new version themselves. The old may not be compatible with the new.

What should I do?

Json. The “devDependencies” in package.json records the development dependencies of the system, and then I can install them in bulk through nodejs’ NPM.

Do an experiment. I will create a new directory “grunt_test_1” under disk E and copy package.json from “grunt_test” to it. When you open the command line, jump to “grunt_test_1” and execute the “NPM install” command to see what happens.

Press Enter to execute the command, resulting in the “node_modules” folder in “grunt_test_1”, where the plugins configured in “devDependencies” in package.json are installed. Also, the version is always the same.

Amazing!!!!

14. System file structure

When you use Grunt to build a Web front-end development environment, the document directory may not be the same as before. Because the code file you write by hand is not the file you end up exporting. These need to be checked, merged, and compressed by various Grunt plugins before they can be exported to the user.

The following screenshot shows an example of a document structure:



In the image above, the “SRC” folder stores the original code files, the “dist” folder stores the generated code files, and the “demo” folder stores some test pages.

Of course, the file structure varies from system to system, but I recommend that you organize your document along these lines. You can also refer to the documentation structure of well-known open source projects such as jQuery and Bootstrap on GitHub. Take a look at how complex the development environment of jQuery is, even though it is a simple JS file.

Reference address: grunt plugin’s official website: http://www.gruntjs.net/plugins for 30 minutes make a pack of grunt front-end code: http://www.cnblogs.com/yexiao… http://blog.csdn.net/wangfupe… http://www.xgllseo.com/?p=4287