gpt4 book ai didi

javascript - 如何遍历数组并运行 Grunt 任务,将数组中的每个值作为 Grunt 选项传递

转载 作者:行者123 更新时间:2023-11-30 07:34:44 25 4
gpt4 key购买 nike

我有一个类似于下面的数组:

var themes = grunt.option('themes') || [
'theme1',
'theme2',
'theme3'
];

还有另一个变量:

var theme = grunt.option('theme') || 'theme1';

这个值在我的 grunt 文件的不同地方使用,例如确定某些 Assets 的路径等。

长话短说,我运行以下命令来编译单个主题的 Assets :

grunt compile --theme=theme2

我正在寻找一种循环遍历主题数组并使用适当的 grunt.option 运行 compile grunt 任务的方法。本质上,我希望实现的目标与此相同:

grunt compile --theme=theme1 && grunt compile --theme=theme2 && grunt compile --theme=theme3

我尝试了以下方法:

grunt.registerTask('compile:all', function() {
themes.forEach(function(currentTheme) {
grunt.option('theme', currentTheme);
grunt.task.run('compile');
});
});

这会运行 compile 任务适当的次数,但是 theme 选项似乎没有设置。所以生成了我的 Scss 文件,但它们是空的。

我也试过这个:

grunt.registerTask('compile:all', function() {
themes.forEach(function(currentTheme) {
grunt.util.spawn({
grunt : true,
args : ['compile', '--theme=' + currentTheme]
});
});
});

任务几乎立即完成并显示“成功”消息,但它似乎没有执行任何操作。

我尝试的最后一件事与上面的类似,除了我尝试使用异步:

grunt.registerTask('compile:all', function() {
themes.forEach(function(currentTheme) {
var done = grunt.task.current.async();
grunt.util.spawn({
grunt : true,
args : ['compile', '--theme=' + currentTheme]
}, done);
});
});

但是这个任务失败了。我不太确定哪里出错了,

感谢您的帮助

最佳答案

我认为你的问题是你的个人编译任务被 grunt.task.run('compile'); 排队,但是,当它们执行时,你的 themes.forEach 循环已完成,您的 theme 选项设置为 themes 中的最后一个值。

我认为您需要注册一个单独的任务,负责设置theme 选项 运行编译任务。

grunt.registerTask('compile_theme', function (theme) {
grunt.option('theme', theme);
grunt.task.run('compile');
});

您可以在您的每个主题的 compile:all 任务中加入此任务:

themes.forEach(function(currentTheme) {
grunt.task.run('compile_theme:' + currentTheme);
});

如果您希望能够在命令行指定要编译的主题,您需要更新您的 compile:all 任务以读取所有 --theme= 参数并强制该值是一个数组:

grunt.registerTask('compile:all', function () {
var compileThemes = grunt.option('theme') || 'theme1';

if (grunt.util.kindOf(compileThemes) === 'string') {
compileThemes = [compileThemes];
}

compileThemes.forEach(function(currentTheme) {
grunt.task.run('compile_theme:' + currentTheme);
});
});

您可以按如下方式调用命令:

grunt compile:all // compiles 'theme1'
grunt compile:all --theme=theme2 // compiles 'theme2'
grunt compile:all --theme=theme2 --theme=theme3 // compiles 'theme2' and 'theme3'

注意:此时您可能想要重命名您的 compile:all 任务,因为它不再需要编译所有 主题。

编辑

它不起作用,因为我们对 theme 选项的期望过高。我们正在尝试使用它来获取在命令行中输入的主题,以在我们的配置中动态组合值(例如,dest: theme + '/app.js'. 按照我构建答案的方式,theme 不能在配置中使用。

我会为将在配置中使用的 theme 使用配置变量。这意味着更新 compile_theme 任务:

grunt.registerTask('compile_theme', function (theme) {
grunt.config('theme', theme);
grunt.task.run('compile');
});

我们需要通过用模板字符串替换 theme 来更新我们的配置。例如:

dest: '<%= theme %>/app.js'

关于javascript - 如何遍历数组并运行 Grunt 任务,将数组中的每个值作为 Grunt 选项传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37714973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com