Grunt plugin Quick Start tutorial

Source: Internet
Author: User
Tags generator install node git clone

Here we record some key points of Grunt plug-in development. As a note, it is concise and concise. It is more suitable for students who know Grunt. Note: In this example, Linux or OS X may be slightly different in windows.


I. Environment preparation

1. Install Node. js

Download and install the appropriate version on the Node. js official website. After the installation is complete, open the cmd command window and enter node-v. If the version number is output, the installation is successful.

2. Install grunt-cli

According to Grunt's official documents, open the cmd command window and enter npm install-g grunt-cli for installation. After the installation is complete, enter grunt-version. If the version number is output, the installation is successful.

Note: The default npm source download package address is abroad. For some reason, the download speed may be slow. We recommend that you use domestic images, such as Taobao npm images. If it is used in the intranet, it may also involve configuring a proxy for normal access.

3. Install the appropriate IDE

I recommend using webstorm because its debugging function is very useful. Of course, other development tools are also OK, just use them.

4. Install Git

Unless you are not planning to use Git for version management (of course you can also choose SVN and so on) your plug-in, otherwise windows users need to go to the https://git-for-windows.github.io/download installation; if you need visualization tools, you can install TortoiseGit after installing Git.

5. Register an account in GitHub

Unless you are not planning to use your plug-in to manage source code using GitHub (and you have many other options, of course), you need to go to https://github.com/for registration.

6. Register an account in npm

Unless you are not planning to upload your plug-in to npm, you need to go to https://www.npmjs.com/for registration.


2. Create a project

1. Name of the Grunt plug-in

To develop a Grunt plug-in, you must first have a name that fits (liang. According to the conventions, the Grunt plug-in is named after grunt-, but note the following:

The "grunt-contrib" namespace is reserved for the tasks maintained by the Grunt team. We should avoid using it;

After confirming the name, please search for it on the npm official website to see if it has been occupied. If it has been occupied, please change the name.

In this example, we call this plug-in grunt-mytest.

2. Create a project

If the plug-in name is determined, a new project is created. For example, our project path is D: \ code \ grunt-mytest.

3. Create a GitHub repository

Although not necessary, it is necessary to establish a repository for tracking such as source code management and issue. Generally, if your plug-in is open-source, GitHub is recommended, and Git @ OSC is available in China. For example, the github repository address we applied for is: https://github.com/helinjiang/grunt-mytest, and the process is:




III. Use project scaffolding

Currently, there are two main ways to quickly generate project scaffolding, one is officially recommended to use the grunt-init tool, and the other is to use Yeoman.

Method 1: grunt-init and grunt-init-gruntplugin

Officially recommended method. Refer to the official guidelines for the following:

1. Install grunt-init

Run the npm install-g grunt-init command to install grunt-init.

2. Install gruntplugin

Clone git through git: // github.com/gruntjs/grunt-init-gruntplugin.git ~ /. Grunt-init/gruntplugin command to install the grunt plug-in template. However, note that in windows, the address to be saved must be changed to % USERPROFILE % \. grunt-init \ gruntplugin, where % USERPROFILE % is generally C: \ Users \ [user].

If git is not installed in the current system, go to GitHub to download grunt-init-gruntplugin and place the content in C: \ Users \ [user] \. grunt-init \ gruntplugin directory.

Note: A folder cannot be directly named in window. grunt-init, you can use the cmd command, cd to C: \ Users \ [user], and then enter the command: md. grunt-init.

3. Execute grunt-init gruntplugin

In cmd, cd to D: \ code \ grunt-mytest, execute grunt-init gruntplugin, interactive Q & A will appear, step by step, for example:


Method 2: Yeoman and generator-gruntplugin

Refer to the instructions in the generator-gruntplugin document and sort them out as follows:

1. Install Yeoman

Go to the Yeoman official website and follow the prompts to install Yeoman.

Run npm install-g yo to install Yeoman and run yo -- version to check whether the installation is successful.

2. Install generator-gruntplugin

Run npm install-g generator-gruntplugin.

3. Execute yo gruntplugin

In cmd, run cd to D: \ code \ grunt-mytest and run yo gruntplugin. An interactive Q & A will appear, and you can proceed step by step.

4. Before development

It is necessary to add some skills before writing the code.

1. Directory structure of scaffolding

The significance of scaffolding is to provide a template so that we can write our plug-ins in this way. Therefore, before writing code, let's first look at its Directory structure (only show important files ):


|-Task
|-Mytest. js
|-Test
|-Expected
|-Custom_options
|-Default_options
|-Fixtures
|-123.
|-Testing
|-Mytest_test.js
|-Gruntfile. js
|-Package. json


Here, our task is in/tast/mytest. js. The unit test case is In/test/mytest_test.js. The building task of the automatically generated project is very simple, that is, to merge multiple files and provide two options. After running the grunt command, the build starts and the unit test is also executed.

2. Documentation

We need some necessary documents, including APIs:

Creating plugins

Grunt API

Node. js API

Grunt is based on Node. js development, so theoretically use Node. js APIs can do a lot of things, but we recommend using the APIs provided by Grunt as much as possible to improve development efficiency.


5. Under development

In our example, we mainly deal with the/tasks/mytest. js file, because our task is defined here. Since each plug-in has different purposes, too many programming details cannot be discussed. Here we only discuss a few points.

1. Do not build a car behind closed doors

Each Grunt plug-in has a specific purpose, but it is nothing more than "processing certain files (src) based on certain configurations (options ", in addition, each task may have multiple target targets. The most difficult thing is to get familiar with how the set is played and the rules (for example, how to obtain all valid src files, how to save files, and how to process multiple targets ), the rest is easy.

If we do not have enough experience, the best way is to refer to how many plug-ins are currently used, especially the official plug-ins. For example, grunt-contrib-clean and grunt-contrib-copy are two typical examples based on different processing methods for src files.

Grunt-contrib-clean directly operates src. Its typical usage is as follows. It is suitable for scenarios where the original file is processed directly, such as my grunt-file-modify.


Clean :{
Build :{
Src: ["path/to/dir/one", "path/to/dir/two"]
    }
Release: ["path/to/another/dir/one", "path/to/another/dir/two"]
}


Grunt-contrib-copy needs to be configured with src and dest. The typical usage is as follows. This should be the case for most Grunt plug-ins.

Copy :{
Build :{
Src: 'src /*',
Dest: 'dest /',
},
Release :{
Files :[
            {
Expand: true,
Cwd: 'Path /',
Src: ['**'],
Dest: 'dest /'
},
],
},
}


The reason why I give this example is only to illustrate that in addition to viewing the API, we also need to look at the code of other people, so that we can have a deeper understanding.

2. Breakpoint, single-step debugging

I mentioned earlier that webstorm is recommended, mainly because it is very easy for breakpoint debugging. For a while, I like to use the console platform to print logs for debugging. Later, I found that this method is very inefficient. I know some of my colleagues are the same as me, I am not used to single-step debugging, which is why I want to emphasize it here.

Please try to use one-step debugging, because you can find a lot of details during the debugging process. These details cannot be obtained by simply checking information and reading documents. For example, during the development process. in registerMultiTask, you need to obtain the target name of the current task execution, that is, when grunt copy: build is executed, I can obtain target = "build". When grunt copy: release is executed, I can get target = "release ". Through the breakpoint, I found three possible values:

Grunt. task. current. name: the name of the currently called task. Both values are "copy", which does not meet my expectation.

Grunt. cli. tasks [0]: name of the task called at the outermost layer, which is target = "copy: build" and target = "copy: release", which does not meet my expectations.

This.tar get: target = "build" and target = "release", meeting my expectations


3. Iteration by function

After a functional block is completed and the test is normal, the code is merged in time for iterative development. Do not merge a lot of changes in one breath. This will not only fail to track the code merging, but also cause a major problem if the code is rolled back after an error occurs.

At the same time, if the function has been basically completed (you can also do so from the very beginning), you can use issue to track bugs and new requirements. If you are using GitHub to manage source code (other functions may also be available), after you create an issue, if you enter the isuue URL in the integration record when you merge the code, the issue automatically manages the integration record, this also means that you can find the corresponding code for every issue. You can go to the https://github.com/helinjiang/grunt-htmlstamp/issues/2 to see the effect:



VI. Unit testing

Do not be lazy. Be sure to write the corresponding unit test. Some may be in trouble, but in my personal experience, it brings far more benefits than the so-called "trouble ". In particular, when your functions increase, each modification may affect the previous OK code. Manual inspection of the code alone cannot guarantee the quality of the code.

In this example, write the unit test case in/test/mytest_test.js.

Although it is difficult to achieve the full coverage of test cases in all scenarios, it also takes a lot of time to write test cases, but it is necessary to cover the main scenarios. Before merging or releasing code, make sure that all written use cases have passed the unit test.


VII. readme. md

Scaffolding has helped us generate a copy, and we only need to complete it on this basis. It is a description of our plug-ins, so you can describe the usage as much as possible so that others can quickly get started with your plug-ins.


8. Release to npm

If you have already registered an account in https://www.npmjs.com/, first add that user information to your local environment. Enter npm login in cmd and log on to the client as prompted. If you have not uninstalled npm, you generally only need to log on once.

If you have logged on to the client, run cd to D: \ code \ grunt-mytest and run npm publish. Of course, because we demonstrate an example, it will not be actually published to npm.

After the release is successful, you can search your plug-in the https://www.npmjs.com/, or enter the https://www.npmjs.com/package/grunt-mytest directly to enter your plug-in home page.


9. Difficulties

Note that if readme. md contains Chinese characters. Check whether the file is encoded in UTF-8 format. Otherwise, even if it is displayed normally in GitHub, Chinese characters are garbled on the npm website.

Npm publish to npm, npmjs.com data may not be refreshed in real time, and its reademe. md information is the same, it may take several minutes. At the same time, synchronization of various npm images also takes some time (you can also manually trigger synchronization ).

In the interactive Q & A generated by scaffolding, do not enter single or double quotation marks in the description. Otherwise, the generated code may have problems (you can try it yourself ). Even if escape characters are used, there may be some unexpected scenarios.

If we modify readme. md. Every time the pull code is sent to GitHub, the latest document is displayed on GitHub. However, when we run npm publish to npm, we find that the document above npm is not updated. Unless you have modified the version number in package. json.


Grunt plug-in development and adjustment


Grunt plug-in development steps

Install grunt-init with npm install-g grunt-init
Install the gruntplugin template with git clone git: // github.com/gruntjs/grunt-init-gruntplugin.git ~ /. Grunt-init/gruntplugin
Run grunt-init gruntplugin an empty directory.
Run npm install to prepare the development environment.
Author your plugin.
Run npm publish to publish the Grunt plugin to npm!

Webstorm debugging

WebStrom is a javascript IDE developed by jetbrains. It is paid and has powerful functions.

1. First, make sure that nodejs is installed.

2. open webstrom and open the project directory created above

3. Choose Run> Edit configrations on the toolbar.
   


4. Click the green icon and select Node. js.

Javascript file: Select the grunt program instead of Gruntfile. js.

Application parameters: test, which indicates to start the grunt test command.

   


Now you can debug gurnt.

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.