我在一个项目上运行许多繁重的任务。其中之一设置了一些 grunt.options grunt.option(key, value)
我需要在后续任务中访问它们 var option = grunt.option(key)
.当我尝试在后一个任务中访问它们时,这些选项返回 undefined
。
如果我在后一个任务的头部记录变量,它会在该任务运行之前显示,并且我无法访问之前在任务配置中设置的值。
在设置 grunt.option 和在另一个任务中使用它以通知 grunt 更改之间,我需要做些什么吗?我在这里做错了什么吗?或者有没有更好的方法来使用各种全局变量(我的研究指出我使用 grunt.option)
我的 Gruntfile.js
grunt.log.writeln('loading tasks');
grunt.loadTasks('grunttasks');
grunt.log.writeln('tasks loaded');
grunt.registerTask(
'jenkins',[
'clean', //clears out any existing build folders
'curl', //gets build config file from remote server
'set-env', //sets the grunt.options based on the build config file
'string-replace:config', //attempts to access the new grunt.options
....
....
....
....
]
);
在我的 set-env 任务中,我根据 curl 任务返回的文本文件的内容设置了一些环境变量。这工作正常,我可以在设置它们后立即记录所有 grunt.options,所以我知道它们设置正确。
设置环境任务
module.exports = function(grunt) {
grunt.registerTask('set-env', 'set-env', function() {
......
......
for (var i = 0; i < propFile.length; i++) {
if (propFile[i] !== '') {
......
......
keyValues[propName] = propValue;
grunt.option(propName, propValue);
console.log("FROM GRUNT.OPTION " + grunt.option(propName));
......
......
}
}
......
......
});
};
当我尝试从我的字符串替换(或任何其他后续)任务访问上述任务中设置的 grunt.options 时,返回 undefined
。如果我在 Gruntfile.js 的开头为这些 grunt.options 设置测试值,我可以毫无问题地访问它们:
module.exports = function(grunt) {
grunt.config('string-replace', {
..........
..........
config:{
files: configFiles,
options: {
replacements: [
..........
..........
{
pattern: /var _OPTION_KEY = \"(.*?)\"\;/ig,
replacement: 'var _OPTION_KEY = "'+grunt.option('_OPTION_KEY')+'";' //grunt.option('_OPTION_KEY') here is undefined
}
..........
..........
]
}
}
..........
..........
});
grunt.loadNpmTasks('grunt-string-replace');
}
(我已经双重、三次和四次检查我使用的是正确的选项键)
最佳答案
问题是,在您在 set-env
中设置选项之前,您正在从任务的“配置阶段”期间设置的 grunt 选项访问变量,该任务运行一次任务。在代码中评估自定义选项键确实应该产生 undefined
。 (请注意,这实际上等同于使用 initConfig block )
您要做的不是从选项对象中读取选项值,而是使用 grunt.config.set
直接修改任务的配置对象。 ,这将使您能够完成您一直在尝试的事情。
所以基本上,而不是
grunt.option(propName, propValue);
使用类似的东西
grunt.config.set('mytask.replacements', options.replacements);
(当然,这将需要对您的代码进行大量修改,我不会深入讨论。)
编辑:可能有一个使用 grunt 模板功能的更简洁的解决方案,请参阅 this stackoverflow answer , 和咕噜 api docs on templating :
Template strings can be processed manually using the provided template functions. In addition, the config.get method (used by many tasks) automatically expands <% %> style template strings specified as config data inside the Gruntfile.
重点是这些不是在解析配置 block 时计算的,而是仅在任务使用 config.get
读取值时计算的。
如果在您的两个自定义任务之间使用选项对象在任务之间共享值的模式效果更好 - 您可以在一个任务中设置它,在另一个任务中读取它,而不是在配置中,而是作为一个实际步骤运行任务。
总的来说,虽然这看起来可行,但我想说这不是 grunt 想要的工作流程——如果你知道你在哪个环境中运行 grunt,通过选项命令传递环境参数会更容易——当您运行 grunt 任务时直接标记行,这将在您正在执行的任何任务配置中生效。
关于javascript - 上一个任务设置的 Grunt 任务 grunt.option 返回 undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30936658/