注册代码位于外部JavaScript文件中的Grunt任务

时间:2013-09-05 13:34:31

标签: javascript requirejs gruntjs

我写了一个我想用作Grunt任务的函数。我可以通过将其添加到Gruntfile来完成此操作:

grunt.registerTask('foo', function () {
    // code here
});

但是,将功能代码保存在单独的文件中更有意义。我计划定义一堆这些自定义任务,我不想膨胀Gruntfile。

我不确定注册此类任务的首选方式是什么。我发现这个工作:

grunt.registerTask('foo', function () {
    require('./path/to/foo.js')(grunt);
});

所以,我有第一个例子中的内联函数,但这一次,我正在加载一个外部文件并立即调用它。在那个外部文件中,我当然要写:

module.exports = function (grunt) {
    // code here
}

这很有效,但感觉很乱。有没有更合适的方法呢?

2 个答案:

答案 0 :(得分:23)

简短回答:替代

grunt.registerTask('foo', function () {
    require('./path/to/foo.js')(grunt);
});

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

但是,如果您不想将任何内容上传到注册表,则应使用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
        }
    }
});

答案 1 :(得分:0)

我有类似的问题。

我想通过功能(大型UX / UI块)而不是技术功能模块化我的grunt配置和自定义任务。我希望将配置文件保留在任务文件旁边...(更好地处理具有不同团队的大型遗留代码库 - 具有不同JS知识的5个人)

所以我把我的任务外化了,就像克拉西米尔那样。

在gruntfile中,我写道:

//power of globbing for loading tasks
var tasksLocations = ['./grunt-config/default_tasks.js', './grunt-config/**/tasks.js'];

var taskFiles = grunt.file.expand({
    filter: "isFile"
  }, tasksLocations);

taskFiles.forEach(function(path) {
  grunt.log.writeln("=> loading & registering : " + path);
  require(path)(grunt);
});

你会在这里找到整个样板文件gruntfile(外部配置和任务加载): https://gist.github.com/0gust1/7683132