Nodejs Grunt 插件开发指导

Nodejs Grunt 插件开发指导

感觉现在的 Github 上的教程越发的难懂了, 看了也不知道怎么写 https://github.com/gruntjs/grunt/wiki/Creating-plugins 我现在的大概能理解的是在 tasks/ 目录下写一个脚本来跑应用 大概也是 registerTask 大概的原理, 但我不知道 Grunt 是怎样加载进来那个脚本的 而且, 官方给了一个基本的测试, 但是… 看不懂, 请问有没有指导一下


7 回复

当然可以。以下是一篇关于如何编写 Node.js 的 Grunt 插件的指南,旨在帮助你理解 Grunt 插件的基本结构和工作原理。

Node.js Grunt 插件开发指导

Grunt 是一个基于任务的 JavaScript 构建工具,它可以帮助开发者自动化重复的任务。为了创建一个 Grunt 插件,你需要了解一些关键的概念和步骤。以下是一个简单的指南,包括一些示例代码。

1. 创建一个新的插件项目

首先,创建一个新的文件夹来存放你的插件代码。例如:

mkdir my-grunt-plugin
cd my-grunt-plugin
npm init -y

这会生成一个 package.json 文件,这是所有 npm 包的基础。

2. 编写插件代码

在项目的根目录下创建一个 tasks 文件夹,并在其中创建一个 JavaScript 文件。假设我们创建了一个名为 myplugin.js 的文件:

// tasks/myplugin.js
module.exports = function(grunt) {
  grunt.registerMultiTask('myplugin', 'A simple plugin that does something', function() {
    var options = this.options({
      greeting: 'Hello'
    });

    this.files.forEach(function(f) {
      f.src.filter(function(filepath) {
        // 这里可以添加文件过滤逻辑
        return grunt.file.exists(filepath);
      }).map(function(filepath) {
        var src = grunt.file.read(filepath);
        return options.greeting + ', ' + src;
      }).forEach(function(content) {
        grunt.file.write(f.dest, content);
      });
    });
  });
};

3. 注册插件

在你的插件的 package.json 文件中添加 gruntPlugin 字段,以便 Grunt 能够识别并加载你的插件:

{
  "name": "my-grunt-plugin",
  "version": "0.1.0",
  "description": "A simple Grunt plugin",
  "main": "tasks/myplugin.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Your Name",
  "license": "MIT",
  "gruntPlugin": true
}

4. 使用插件

在你的 Gruntfile.js 中,你可以像使用其他插件一样使用这个插件:

// Gruntfile.js
module.exports = function(grunt) {
  require('load-grunt-tasks')(grunt);

  grunt.initConfig({
    myplugin: {
      options: {
        greeting: 'Hi'
      },
      files: {
        'dest/output.txt': ['src/input.txt']
      }
    }
  });

  grunt.registerTask('default', ['myplugin']);
};

5. 测试插件

Grunt 提供了一种简单的方式来测试你的插件。你可以使用 grunt 命令行工具运行测试,或者在插件中编写单元测试。例如,你可以使用 Mocha 和 Chai 来编写测试:

// tests/test-myplugin.js
var assert = require('assert');
var grunt = require('grunt');

exports['myplugin'] = {
  setUp: function(done) {
    done();
  },
  'basic functionality': function(test) {
    var actual = grunt.file.read('dest/output.txt');
    var expected = 'Hi, some content from input.txt';
    test.equal(actual, expected, 'should write the expected file.');
    test.done();
  }
};

通过以上步骤,你应该能够创建并使用自己的 Grunt 插件。希望这些信息对你有所帮助!如果你有任何问题或需要进一步的帮助,请随时提问。


是不是可以参考别人现成的例子? 比如 grunt-contrib-coffee https://npmjs.org/package/grunt-contrib-coffee https://github.com/gruntjs/grunt-contrib-coffee

不过,我觉得这个插件就是让你本来的task和配置文件变成自动的,省的你自己配置了吧?

Many commonly used tasks like concatenation, minification and linting are available as grunt plugins. As long as a plugin is specified in package.json as a dependency, and has been installed via npm install, it may be enabled inside your Gruntfile with a simple command: grunt.loadNpmTasks(‘grunt-contrib-coffee’);

http://gruntjs.com/getting-started#loading-grunt-plugins-and-tasks

那么既然如此,写这个plugin就应该和写一个npm模块差不多的写法,遵照http://gruntjs.com/creating-plugins 这里的写法,最后npm publish就可以了。

不过,我自己没玩这个grunt。 没有亲自动手,不知道里面的难点。 只能提出自己的一点拙见。

附带seajs里面的文章 SeaJS 打包的 grunt 任务 https://groups.google.com/d/topic/seajs/UTeDYW_572U/discussion

一个巨大的问题是 Task 写好以后, 里边起的 HTTP 服务器不能保持监听状态直接退出了 我在看到一个 watch 的 demo, 其中是这样的, https://github.com/gruntjs/grunt-contrib-watch/blob/master/tasks/watch.js#L108

// Keep the process alive
setInterval(function() {}, 250);

可我在我的插件里, 同时起了 HTTP 和 ws, 加上这样的循环, 还是退出了 也没有报错, 不明白…

嗯, 参考已有的插件是觉得简单过了

嗯, 参考已有的插件是觉得简单过了

为什么我的异步任务没有完成? 可能由于你忘记调用this.async方法来告诉Grunt你的任务是异步的,那么就可能会发生这种情况(异步任务失败)。为了简单起见,Grunt使用同步的编码风格,可以在任务体中通过调用this.async将该任务(调用这个方法的任务)转换为异步的。

注意传递false给done函数就会告诉Grunt任务已经失败。

例如:

grunt.registerTask(‘asyncme’, ‘My asynchronous task.’, function(){ var done = this.async(); doSomethingAsync(done); });

http://www.gruntjs.org/article/creating_tasks.html

创建一个Grunt插件主要包括以下几个步骤:

  1. 初始化项目:使用npm init创建一个新的Node.js项目,并且安装grunt作为开发依赖。

    npm init -y
    npm install grunt --save-dev
    
  2. 创建任务文件:在tasks目录下创建一个JS文件(如mytask.js),并在该文件中定义任务逻辑。例如:

    module.exports = function(grunt) {
        grunt.registerMultiTask('hello', 'Log some greetings.', function() {
            var util = require('util');
            this.files.forEach(function(f) {
                f.src.forEach(function(filepath) {
                    grunt.log.writeln(util.format('hello %s', filepath));
                });
            });
        });
    };
    
  3. 配置任务:在你的Gruntfile.js中注册并配置这个新任务。例如:

    module.exports = function(grunt) {
        grunt.initConfig({
            pkg: grunt.file.readJSON('package.json'),
            hello: {
                options: {},
                files: {
                    src: ['path/to/file1', 'path/to/file2']
                }
            }
        });
    
        // 加载包含 "hello" 任务的插件。
        grunt.loadTasks('tasks');
    
        // 默认被执行的任务列表。
        grunt.registerTask('default', ['hello']);
    };
    
  4. 编写测试:Grunt插件通常需要一些单元测试来确保其行为符合预期。你可以使用Jasmine或Mocha等测试框架。例如,在test目录下创建一个测试文件hello_test.js:

    const assert = require('assert');
    const hello = require('../tasks/hello');
    
    describe('hello task', function() {
        it('should log hello messages', function() {
            const options = {};
            const files = [
                {src: ['path/to/file1']}
            ];
            hello.init(options);
            hello(files);
            // 这里可以添加更多断言来验证任务的行为
        });
    });
    
  5. 发布到NPM:当你的插件准备好了,你可以将其发布到NPM,让其他人也可以使用它。在package.json中添加必要的字段,然后运行npm publish

以上就是一个基本的Grunt插件开发流程。希望这些信息对你有所帮助!

回到顶部