![](/img/trans.png)
[英]Requirejs and Grunt: mainConfigFile vs grunt task options
[英]Programmatically set options for grunt task?
我有一个grunt任务,用grunt.option('foo')
查看选项。 如果我从grunt.task.run('my-task')
调用此任务, grunt.task.run('my-task')
该如何更改这些参数?
我正在寻找类似的东西:
grunt.task.run('my-task', {foo: 'bar'});
这将相当于:
$ grunt my-task --foo 'bar'
这可能吗?
( 这个问题是我遇到的另一个问题,但并不完全相同,因为在这种情况下我无法访问原始任务的Gruntfile.js。)
如果您可以使用基于任务的配置选项而不是grunt.option,那么这应该可以为您提供更精细的控制:
grunt.config.set('task.options.foo', 'bar');
看起来我可以使用以下内容:
grunt.option('foo', 'bar');
grunt.task.run('my-task');
设置全局选项而不仅仅是针对该命令感觉有点奇怪,但它有效。
创建一个新任务,设置该选项,然后调用修改后的任务。 这是汇编的真实例子:
grunt.registerTask('build_prod', 'Build with production options', function () {
grunt.config.set('assemble.options.production', true);
grunt.task.run('build');
});
除了@Alessandro Pezzato
Gruntfile.js:
grunt.registerTask('build', ['clean:dist', 'assemble', 'compass:dist', 'cssmin', 'copy:main']);
grunt.registerTask('build-prod', 'Build with production options', function () {
grunt.config.set('assemble.options.production', true);
grunt.task.run('build');
});
grunt.registerTask('build-live', 'Build with production options', function () {
grunt.option('assemble.options.production', false);
grunt.task.run('build');
});
现在你可以跑了
$ grunt build-prod
-要么-
$ grunt build-live
他们都将执行完整任务'build'并分别将值传递给汇编选项之一 ,即生产'true'或'false'。
除了说明组装示例之外:
在汇总时,您可以选择添加{{#if production}}do this on production{{else}}do this not non production{{/if}}
grunt是所有程序化的..所以如果您之前已经设置了任务选项,那么您已经以编程方式完成了此操作。
只需使用grunt.initConfig({ ... })
来设置任务选项。
如果你已经初始化,并且之后需要更改配置,你可以做类似的事情
grunt.config.data.my_plugin.goal.options = {};
我正在将它用于我的项目并且它有效。
我最近遇到了同样的问题:以编程方式在单个父任务中多次设置grunt选项和运行任务。 正如@Raphael Verger所提到的,这是不可能的,因为grunt.task.run
将任务的运行推迟到当前任务完成:
grunt.option('color', 'red');
grunt.task.run(['logColor']);
grunt.option('color', 'blue');
grunt.task.run(['logColor']);
将导致蓝色被记录两次。
经过一番摆弄后,我想出了一个笨拙的任务,允许为每个要运行的子任务动态指定不同的选项/配置。 我已经将这项任务发布为grunt-galvanize 。 以下是它的工作原理:
var galvanizeConfig = [
{options: {color: 'red'}, configs: {}},
{options: {color: 'blue'}, configs: {}}
];
grunt.option('galvanizeConfig', galvanizeConfig);
grunt.task.run(['galvanize:log']);
通过使用galvanizeConfig
指定的每个选项/配置运行日志任务,这将根据需要记录红色然后蓝色 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.