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

2024-02-19

我编写了一个函数,我想将其用作 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
}

这可行,但感觉很黑客。有更正确的方法吗?


简短的回答:替代方案

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
        }
    }
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐