求 Grunt 插件开发指导...
发布于 11 年前 作者 jiyinyiyong 6847 次浏览 最后一次编辑是 8 年前

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

6 回复

是不是可以参考别人现成的例子? 比如 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

@aidenli 有道理有道理, 再遇到要看下这个地方

回到顶部