The*_*ter 6 javascript gruntjs
我有几个笨拙的任务,我试图分享这些任务的全局变量,我遇到了问题.
我编写了一些自定义任务,根据构建类型设置正确的输出路径.这似乎是正确的设置.
// 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);
});
Run Code Online (Sandbox Code Playgroud)
所以,我试图在后续任务中引用global.outputPath,然后遇到错误.
如果我grunt test从命令行调用,它输出正确的路径没问题.
但是,如果我有这样的任务:clean:{release:{src:global.outputPath}}
它会引发以下错误:
Warning: Cannot call method 'indexOf' of undefined Use --force to continue.
另外,setOutput任务中的常量设置在我的Gruntfile.js的顶部
有什么想法吗?我在这里做错了吗?
The*_*ter 13
所以,我走的是正确的道路.问题是模块在设置全局变量之前导出,因此在initConfig()任务中定义的后续任务中它们都是未定义的.
我提出的解决方案虽然可能更好,但是要覆盖grunt.option值.
我的任务有一个可选选项--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"));
});
Run Code Online (Sandbox Code Playgroud)
initConfig()中定义的任务如下所示:
clean: {
build: {
src: ["<%= grunt.option(\"target\") %>"]
}
}
Run Code Online (Sandbox Code Playgroud)
如果您有更好的解决方案,请随意加入.否则,也许这可能会帮助别人.