在 Grunt 中使用全局变量设置构建输出路径

2024-03-22

我有几个繁重的任务,我试图在这些任务之间共享全局变量,但我遇到了问题。

我编写了一些自定义任务,它们根据构建类型设置正确的输出路径。这似乎是正确的设置。

// 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从命令行,它输出正确的路径没有问题。

但是,如果我有这样的任务: 干净的: { 发布: { src: 全局.outputPath } }

它抛出以下错误:Warning: Cannot call method 'indexOf' of undefined Use --force to continue.

另外,setOutput 任务中的常量设置在 Gruntfile.js 的顶部

有什么想法吗?我在这里做错了什么吗?


所以,我走在正确的道路上。问题是模块在设置这些全局变量之前导出,因此它们在 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"));
});

initConfig() 中定义的任务如下所示:

clean: {
  build: {
    src: ["<%= grunt.option(\"target\") %>"]
  }
}

如果您有更好的解决方案,请随时参与。否则,也许这可能对其他人有帮助。

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

在 Grunt 中使用全局变量设置构建输出路径 的相关文章

随机推荐