Grunt plug-in production

Source: Internet
Author: User

Plugin content: Add a character draw at the top of the file.

A project from scratch, so we need to initialize the project with Yeoman. On the Yeoman official website of the generator storage page search Gruntplugin.

Install this generator:

NPM install-g generator-gruntplugin//generator naming rules: Genetator-generator's name

Generate Project Code

Yo gruntplugin grunt-buddha//yo generator name Item name

Then CMD will appear the project configuration information, custom input, generate Package.json. The generated project directory

The plugin code is stored in the Tasks folder, and the tasks file name cannot be changed.

Download character painting

Find a few characters on the Internet to save to the Assert directory under Tesks, here I found a mianyang and horse.

Core work code generated by Gruntplugin

' Use strict ';  Use ES5 Strict mode  function//"warp" functions  //grunt.registermultitask: Allows multiple target to be configured for one plug-in, ' Buddha_liu ': The name of the plugin, ' the best Grunt plugin ever. ' : Description of plugin, fn: Plugin core function
Grunt.registermultitask (' Buddha_liu ', ' the best Grunt plugin ever. ',function() { //Set the default value of the plug-in property, if the plug-in defines the punctuation is overwritten, a bit like the Extend method of jquery.
The This here refers to the configuration properties configured in Gruntfile.
varOptions = This. Options ({punctuation:‘.‘, Separator:‘, ‘ }); //the file format in the Gruntfile configuration, regardless of the form, is converted to a format in the form of a file array, eg:
files:[
{
src:[' src/aa.js ', ' src/bb.js '],
dest:[' src/aa.min.js ', ' src/bb.min.js ']     
}
//]
//The this.files here is an array of object key values containing the src,dest.
foreach is ECMASCript6 new syntax, and there are three parameters in the formal parameter that iterate over the array callback (VALUE,INDEX,ARR)
This. Files.foreach (function(file) {//connect the specified file
The parameters are similar to foreach.
    //filter is also required ECMASCRIPT6 the new syntax. The callback function is a function that accepts up to three arguments. for each element in the array, thefilter method calls the CALLBACKFN function once
The return value of the filter is a new array that contains all the values for which the callback function returns true. if the callback function returns false for all elements of array1, the length of the new array is 0.
    
//Regardless of what SRC is inside the configuration, the file.src here will be converted to the form of an array
varsrc = file.src.filter (function(filepath) {
 //use the API provided by grunt to see if this file exists  if  (!< Span style= "color: #000000;" >grunt.file.exists (filepath) {
// Do not break grunt Task Grunt.log.warn ( ' Source file ' ' + filepath + '" Not found. ' ); return false ; else { return true ; }}). map ( function (filepath) { Span style= "color: #008000;" >
   Filter is also required to ECMASCript6 the new syntax, parameters are similar to foreach, and each element in the array is manipulated to return a new array
        return Grunt.file.read (filepath);       //grunt.util.normalizelf is a method of the grunt API that is used to convert line breaks across systems

src +=// plus end symbol
   The file.dest here will be the value of a string and will not be an arr like file.src.
//write to the destination file grunt.file.write (file.dest, SRC); // give a prompt message to the console. Grunt.log.writeln (' File ' + file.dest + ' "created. ') ); }); });};

Transform the code to achieve our ability to add characters to the top of the file

The first step: Design the configuration content of the gruntfile.js.

' use strict '; module.exports = function Require (' Load-grunt-tasks ') (grunt);Grunt.initconfig ({//Buddha_liu: {
    //because we are adding character painting on the basis of the original file, so we just need a src to do it here.
Configuration parameters for plug-ins
    options:{
Who: ' Sheep ', //need to connect which character to draw, here are horse and sheep two options
      Comentsymbol: "//" character draw the preceding comment symbol
}, dist:{
src:[' Test/fixtures/*.js ']//files that require connection characters to draw
} } });//Grunt.loadtasks (' Tasks ');Grunt.registertask (' Test ', [' Buddha_liu ',]);};

Step Two: Transform the plugin JS file under the Tasks directory

' Use strict '; //Use strict mode varPath = require ("path"); //Load path module module.exports in Nodejs =function(grunt) {Grunt.registermultitask (' Buddha_liu ', ' the best Grunt plugin ever. ',function () {    //Replace plug-in default items    varOptions = This. Options ({who:' Sheep ',//Sheep,horseCommentsymbol: "//"    });
  Character Draw path map
varcommenttextmap={ "Horse": "Assert/horse.txt", "Sheep": "Assert/sheep.txt"}// regular match expression, cannot add the same character multiple times to draw into a file //var testregexmap = { //"Sheep":/_.-----..,-' (' "--^/, //"Horse":/(| y;--,-"'"-.\ \/ // }
//The __dirname here is a global variable in the NODEJS environment to represent the directory where the current running code resides
The path used to find the character draw
varCommentfilepath=Path.join (__dirname,commenttextmap[options.who]);
//Read the contents of a character drawing varcommentfiletext=Grunt.file.read (Commentfilepath);
//Get the character to draw every line of content, here's
varLinecomment = Commentfiletext.split (grunt.util.normalizelf ("\ r \ n"))); //Add a comment symbol to each line of content linecomment= Linecomment.map (function(x) {returnoptions.commentsymbol+x; }) //Compose a new file Commentfiletext=linecomment.join (grunt.util.normalizelf ("\ r \ n")); //traversing the src file list of the Gruntfile configuration     This. Files.foreach (function(file) {File.src.filter (function(filepath) {//Warn on and remove invalid source files (if Nonull is set).        if(!grunt.file.exists (filepath)) {Grunt.log.warn (' Source file ' ' + filepath + ' "not found. '); return false; } Else {          return true; }}). map (function(filepath) {//Reads the contents of the source file, the contents of the characters drawn on the connection         varOrigincontent =Grunt.file.read (filepath), newfilecontent= Commentfiletext + grunt.util.normalizelf ("\ r \ n") +origincontent; //Cannot add the same characters repeatedly to draw into a file //if (testregexmap[options.who].test (origincontent)) {                //return;                // }
Put the attached file, rewrite write to the target file, complete the target
grunt.file.write (filepath,newfilecontent)}) //prints the message, prompting the task to complete.Grunt.log.writeln (' File ' + file.dest + ' "created. ')); }); });};

This completes the production of the grunt plugin, which can then be uploaded to GitHub via Git and then released into the NPM module, which can then be installed directly using the NPM install module.

Grunt plug-in production

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.