Application grunt automatically optimizes the front-end of your project

Source: Internet
Author: User

Not long ago I wrote an application R. JS to optimize your front-end articles and introduce R. JS is a utility that can compress, merge front-end files, and package the entire project. However. when Javascript is put into the project, we have to take into account a problem. Every time the project is maintained, the maintenance personnel enter the RJS running password and re-package the project. This is naturally very cumbersome. In addition, if we use sass to write styles for our project, we may have to open a koala. If we can allow the project to handle all of its own matters, it will be much more beautiful.

To address these problems, today we will use grunt, a more popular tool, to automate front-end transactions (in fact, RJS also uses the Concat and uglify plug-ins of grunt ).

We still use a very simple project named before (you can download this case from my GitHub) as an example. It is a pure project, you have not used any front-end tools to operate on it:

You can try to run the index.html file under the root directory, which will display a slide.

Next we will use grunt to automate front-end transactions on the before project.

Operation requirements

Since grunt is running on node, you are required to install nodejs on your computer (Click here to download it );

Because Sass is used to write Styles, you must install Ruby on your computer (note that Ruby is installed on Mac by default, for Windows or other systems, click here to download and install ).

During installation, it is recommended that you check all the three options that can be selected (especially the second option should be selected to add environment variables). After installation, click "All Programs"-"ruby.13... -"Start command prompt with Ruby": Open the ruby command line interface and enter the command:

Gem install sass

Note that this command must be executed only when FQ is enabled. Otherwise, sass installation may fail:

In addition, when we compile sass later, if the. SCSs file contains Chinese annotations, ruby may fail to recognize Chinese encoding and cause errors. However, the solution is simple. Click here to view

Install grunt CLI

Open node. js command prompt to enter the node command line interface:

On the command line interface, enter the following code and press enter to run the command. This is to install the grunt global command line, so that we can call the grunt command statement anywhere on the computer:

NPM install-G grunt-cli

Grunt Configuration

You can refer to the official introduction to grunt. Although this official guide is poor, it also tells us that grunt configuration is inseparable from two files --Package. JSONAndGruntfile. jsWe usually place them in the project root directory.

Package. JSON is used to record the project name (just a name), version number (just a number of strings), and plug-in dependency, and create a package. JSON does not need to be manual at all. We only need to locate the node command line under the project (Suppose we put the above before project on the E disk), then enter the following command and press enter to execute it, an initialized package is automatically created in the project root directory. JSON file:

NPM init

After you press enter, node will ask you a number of questions, including the project name, version number, and version number. If you are in a mood, you can write it. If you are not in a mood, press enter all the way:

In this case, you will find a file named package. JSON is added to the root directory:

There is a JSON code pre-defined by node for us. However, I do not like to use NPM init to automatically generate package. JSON. Instead, you can manually create a package. JSON file and enter the concise code:

{  "name": "before",  "version": "1.0.0"}

Yes, we only need to initialize the two lines. In fact, I even hope to be brief to only. It is a pity that name and version are two very important attributes for package. JSON, which are indispensable (you can refer to here to learn more about the role of the package. JSON attribute)

Install plug-ins

Grunt is just a carrier. In practice, you must use a variety of grunt plug-ins (a bit like we can install and use various Sb plug-ins on sublime ).

Our before project needs to use the following plug-ins:

Grunt-- Needless to say, grunt itself;

Grunt-contrib-uglify-- The function is to compress the project JS file;

Grunt-contrib-sass-- The function is to compile the sass (compressed version) CSS file in the project;

Grunt-contrib-watch-- The role is to achieve the "Automation" of our initial needs "! Is one of the most important plug-ins! It monitors the changes to the files to be processed and automatically processes the changes. However, it has a problem that every time a change is monitored, all the files being monitored will be processed in weeks;

Grunt-newer-- The function is to handle the watch fault above, so that watch only processes the changed files when it monitors changes to a file.

However, in node, the command to install the grunt plug-in is:

NPM install<Plug-in Name>-- Save-Dev

The "-- save-dev" icon next to it indicates that the dependency is saved as a dependency. After the plug-in is installed, the dependency of the plug-in is written to the package. JSON file. one of the roles of JSON is to record the project's plug-in dependencies ).

Therefore, run the following commands in the root directory of the project to install the plug-in:

NPM install grunt -- save-Dev

NPM install grunt-contrib-uglify -- save-Dev

NPM install grunt-contrib-sass -- save-Dev

NPM install grunt-contrib-watch -- save-Dev

The following warning may be prompted during running:

This is because we didn't write some descriptions or other things in package. JSON, so here warn is easy to ignore.

After the plug-in is installed, you will find that the project root directory contains a folder named "node_modules", which is used to store the installed plug-ins. In addition, when package. JSON is opened, the plugin dependency information is automatically added to it:

Configure the gruntfile. JS File

At first we mentioned that grunt has two indispensable files-package. JSON and gruntfile. JS file, package. JSON is easy to handle. Next, create a gruntfile. JS file and enter the following code:

Module. exports = function (grunt) {grunt. initconfig ({PKG: grunt. file. readjson ('package. JSON '), // The above is fixed, you can copy it without having to worry about it. // The following is the configuration of each plug-in transaction, in no particular order sass: {// grunt-contrib-sass transaction definition tocss: {options: {style: 'compressed ', // compile CSS in compression mode, so we do not need to use the grunt-contrib-cssmin plug-in sourcemap: 'none' // do not configure the output map file}, files: [{expand: True, CWD: 'css ', // SRC:' **/* in the CSS directory :'**/*. SCSs ', // All CSS files DEST: 'css', // output to this directory Ext: '.css '}] }}, uglify: {// grunt-contrib-uglify transaction definition compressjs: {files: [{expand: True, CWD: 'js', // SRC under the JS directory: '**/*. js', // All JS files DEST: 'output/js' // output to this directory}]}, watch: {// grunt-contrib-watch transaction definition all: {files: ['css /**/*. SCSs ', 'js /**/*. js'], tasks: ['newer: sass ', 'newer: uglify'] }}); // grunt. loadnpmtasks () is used to tell grunt which plug-ins should be used in no particular order. loadnpmtasks ('grunt-contrib-Watch'); grunt. loadnpmtasks ('grunt-contrib-uglify '); grunt. loadnpmtasks ('grunt-contrib-sass '); grunt. loadnpmtasks ('grunt-newer '); // grunt. registertask ('default', []) is to tell grunt which transactions to execute after we enter the grunt command in the node command line. registertask ('default', ['newer: sass ', 'newer: uglify', 'Watch ']); // note "newer: XXX "is the event definition of the plug-in grunt-newer, indicating that the transaction after the colon takes effect };

Gruntfile. JS configuration may be a difficulty in configuring grunt. Its role is to tell grunt which plug-ins should be used. (If installed, it does not mean it must be used. Of course, it must be installed) and what transaction operations are required for each plug-in.

In fact, the simplest initialization framework of gruntfile. JS is as follows:

Module. exports = function (grunt) {grunt. initconfig ({PKG: grunt. file. readjson ('package. JSON '), plug-in transaction name :{........ // transaction definition}); // grunt. loadnpmtasks () is used to tell grunt which plug-ins should be used in no particular order. loadnpmtasks ('plug-In name'); // grunt. registertask ('default', []) is to tell grunt which transactions to execute after we enter the grunt command in the node command line. registertask ('default', ['plug-in transaction name']);};

It is easy to understand the meaning of the Code. For more flexible and complex gruntfile. js configurations, click here for instructions.

After everything is done, we can directly input

Grunt

After you press enter to execute the file, it enters the automatic execution status. If there is a JS or SCSs file change, the changed file will be compressed or compiled again:

The example in this chapter uses sass to write styles. If you only write native CSS and want to compress style files, you can use the grunt-contrib-cssmin plug-in, you can click here to view the specific configuration. This article will not go into details.

Sharing ~

Application grunt automatically optimizes the front-end of your project

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.