我想避免重复代码,所以我尝试从 Grunt 文件“a”加载 grunt 任务并在 grunt 文件“b”中使用它们。
这意味着:我想在文件“b”中查看“a”的所有任务(但没有代码),就像对另一个 grunt 文件的引用或模板一样设置。
这是 grunt 文件“b”:
module.exports = function (grunt) {
'use strict';
var karmaGrunt = './../../grunt',
abortHandler = function () {
var errors = grunt.fail.errorcount,
warnings = grunt.fail.warncount;
if (errors > 0 || warnings > 0) {
//run rocketlauncher python script and then stop the grunt runner.
grunt.task.run(["shell:rocketlauncher", "fatal"]);
}
},
fatal = function () {
// this function stops grunt and make the jenkins build red.
grunt.fail.fatal('failed');
};
require("grunt-load-gruntfile")(grunt);
// load grunt task from another file and add it.
grunt.loadGruntfile(karmaGrunt);
//grunt needs to continue on error or warnings, that's why we have to set the force property true
grunt.option('force', true);
grunt.initConfig({
shell: {
options: {
execOptions: {
cwd: '../scripts'
}
},
'rocketlauncher': {
command: './runRocketLauncher.sh'
}
}
});
grunt.loadNpmTasks('grunt-karma');
grunt.loadNpmTasks('grunt-shell');
grunt.registerTask('build-process', ['karma', 'abortHandler']);
grunt.registerTask('abortHandler', abortHandler);
grunt.registerTask('fatal', fatal);
}
这里是文件“a”:
module.exports = function (grunt) {
"use strict";
var eConfig = '../e-specs/karma.config.js',
dConfig = '../d-specs/karma.config.js',
cConfig = '../c-specs/karma.config.js';
grunt.initConfig({
karma: {
options: {
reporters: ['progress', 'coverage', 'threshold']
},
c: {
configFile: cConfig
},
d: {
configFile: dConfig
},
e: {
configFile: eConfig
}
}
});
grunt.loadNpmTasks('grunt-karma');
};
我的文件 b 加载任务“Karma”,但如果我只运行 a 的 grunt 文件,我有 3 个嵌套任务(“e”、“c”、“d”),但如果我从另一个文件加载它们,唯一我能看到的任务是“业力”
错误是:
No "karma" targets found. Warning: Task "karma" failed. Used --force, continuing.
完成,但有警告。
如果我直接在文件“a”中运行相同的任务,该任务运行起来就像一个魅力。
最佳答案
有一个 grunt 插件可以加载另一个 Gruntfile:grunt-load-gruntfile
有了它,您可以合并两个 Grunt 配置,包括已定义的任务。
这是一个例子:
./Gruntfile.js
:
module.exports = function (grunt) {
require("grunt-load-gruntfile")(grunt);
grunt.loadGruntfile("web"); //loads the Gruntfile from the folder web/
grunt.registerTask('showConfig', "shows the current config", function(){
console.log(JSON.stringify(grunt.config(), null, 2));
});
};
和 ./web/Gruntfile.js
中的第二个 Gruntfile。
module.exports = function (grunt) {
grunt.config("WebConfig", "Configuration from the Gruntfile in web/Gruntfile.js");
grunt.registerTask('server', "runs the server",function(){
console.log("just shows this message");
});
};
运行 grunt showConfig
从第一个 Gruntfile 开始执行任务并显示配置,包括在 ./web/Gruntfile.js
中定义的参数。
运行 grunt server
执行来自 ./web/Gruntfile.js
的任务。
关于javascript - 从另一个 gruntfile 加载 grunt 任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29119401/