简短的回答:替代方案
grunt.registerTask('foo', function () {
require('./path/to/foo.js')(grunt);
});
is http://gruntjs.com/api/grunt#grunt.loadtasks http://gruntjs.com/api/grunt#grunt.loadtasks
长答案:
通常,当您在外部文件中有任务时,会充当其他 Nodejs 模块。因此,如果您将在多个项目中使用该内容,您可能需要将其注册到注册表中。稍后在您的 Gruntfile.js 中您将拥有:
grunt.loadNpmTasks('yout-module-here');
grunt 的文档说:
Load tasks from the specified Grunt plugin. This plugin must be installed locally via npm, and must be relative to the Gruntfile
但是,如果您不想将任何内容上传到注册表,则应该使用加载任务 http://gruntjs.com/api/grunt.task#grunt.task.loadtasks
grunt.loadTasks('path/to/your/task/directory');
因此,一旦加载任务,您就可以在配置中使用它。
这是一个放置在外部文件中的简单 grunt 任务:
'use strict';
module.exports = function(grunt) {
grunt.registerMultiTask('nameoftask', 'description', function() {
var self = this;
// this.data here contains your configuration
});
};
后来在 Gruntfile.js 中
grunt.initConfig({
nameoftask: {
task: {
// parameters here
}
}
});