Šim*_*das 15 javascript requirejs gruntjs
我编写了一个我想用作Grunt任务的函数.我可以通过将其添加到Gruntfile来完成此操作:
grunt.registerTask('foo', function () {
// code here
});
Run Code Online (Sandbox Code Playgroud)
但是,将功能代码保存在单独的文件中更有意义.我计划定义一堆这些自定义任务,我不想膨胀Gruntfile.
我不确定注册这些任务的首选方式是什么.我发现这个工作:
grunt.registerTask('foo', function () {
require('./path/to/foo.js')(grunt);
});
Run Code Online (Sandbox Code Playgroud)
所以,我在第一个例子中有内联函数,但这一次,我正在加载一个外部文件并立即调用它.在那个外部文件中,我当然要写:
module.exports = function (grunt) {
// code here
}
Run Code Online (Sandbox Code Playgroud)
这有效,但感觉很乱.有没有更合适的方法呢?
Kra*_*mir 23
简短回答:替代方案
grunt.registerTask('foo', function () {
require('./path/to/foo.js')(grunt);
});
Run Code Online (Sandbox Code Playgroud)
是http://gruntjs.com/api/grunt#grunt.loadtasks
答案很长:
通常,当您在外部文件中有任务时,它们将作为其他nodejs模块.因此,如果您将在多个项目中使用它,您可能希望在注册表中注册它.稍后在您的Gruntfile.js中,您将拥有:
grunt.loadNpmTasks('yout-module-here');
Run Code Online (Sandbox Code Playgroud)
grunt的文档说:
Load tasks from the specified Grunt plugin. This plugin must be installed locally via npm, and must be relative to the Gruntfile
Run Code Online (Sandbox Code Playgroud)
但是,如果您不想将任何内容上载到注册表,则应使用loadTasks
grunt.loadTasks('path/to/your/task/directory');
Run Code Online (Sandbox Code Playgroud)
因此,一旦加载任务,您就可以在配置中使用它.
这是一个放在外部文件中的简单grunt任务:
'use strict';
module.exports = function(grunt) {
grunt.registerMultiTask('nameoftask', 'description', function() {
var self = this;
// this.data here contains your configuration
});
};
Run Code Online (Sandbox Code Playgroud)
后来在Gruntfile.js中
grunt.initConfig({
nameoftask: {
task: {
// parameters here
}
}
});
Run Code Online (Sandbox Code Playgroud)