我有几个繁重的任务,我试图在这些任务之间共享全局变量,但我遇到了问题。
我已经编写了一些自定义任务,这些任务根据构建类型设置正确的输出路径。这似乎设置正确。
// Set Mode (local or build)
grunt.registerTask("setBuildType", "Set the build type. Either build or local", function (val) {
// grunt.log.writeln(val + " :setBuildType val");
global.buildType = val;
});
// SetOutput location
grunt.registerTask("setOutput", "Set the output folder for the build.", function () {
if (global.buildType === "tfs") {
global.outputPath = MACHINE_PATH;
}
if (global.buildType === "local") {
global.outputPath = LOCAL_PATH;
}
if (global.buildType === "release") {
global.outputPath = RELEASE_PATH;
}
if (grunt.option("target")) {
global.outputPath = grunt.option("target");
}
grunt.log.writeln("Output folder: " + global.outputPath);
});
grunt.registerTask("globalReadout", function () {
grunt.log.writeln(global.outputPath);
});
因此,我试图在后续任务中引用 global.outputPath,但遇到了错误。
如果我从命令行调用 grunt test
,它会毫无问题地输出正确的路径。
但是,如果我有这样的任务: 干净的: { 发布: { 来源:global.outputPath }
它抛出以下错误:
警告:无法调用未定义的方法 'indexOf' 使用 --force 继续。
此外,我在 setOutput 任务中的常量设置在我的 Gruntfile.js 的顶部
有什么想法吗?我在这里做错了什么吗?
最佳答案
所以,我走在了正确的道路上。问题是模块在设置这些全局变量之前导出,因此它们在 initConfig() 任务中定义的后续任务中都是未定义的。
尽管可能有更好的解决方案,但我提出的解决方案是覆盖 grunt.option 值。
我的任务有一个 optional --target
工作解决方案如下所示:
grunt.registerTask("setOutput", "Set the output folder for the build.", function () {
if (global.buildType === "tfs") {
global.outputPath = MACHINE_PATH;
}
if (global.buildType === "local") {
global.outputPath = LOCAL_PATH;
}
if (global.buildType === "release") {
global.outputPath = RELEASE_PATH;
}
if (grunt.option("target")) {
global.outputPath = grunt.option("target");
}
grunt.option("target", global.outputPath);
grunt.log.writeln("Output path: " + grunt.option("target"));
});
initConfig() 中定义的任务如下所示:
clean: {
build: {
src: ["<%= grunt.option(\"target\") %>"]
}
}
如果您有更好的解决方案,请随时提出意见。否则,也许这可以帮助其他人。
关于javascript - 在 Grunt 中使用全局变量设置构建输出路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15647484/