我在我的项目中添加了 Grunt 构建自动化。
我已经创建了一个自定义任务,它为其他任务设置了一个变量,现在我想使用我设置的值来运行该任务。
grunt.registerTask('dist-flow', function () {
if (!grunt.option('env')) {
grunt.option('env', 'prod');
console.log(grunt.option('env'));
}
grunt.registerTask('dist',['dev_prod_switch']);
grunt.task.run('distdev');
});
但是每当我运行 dist-flow
任务时,它都会将 env
设置为 prod
但 dev_prod_switch
始终采用我为 dev_prod_switch
设置的默认值。
所以我想设置任务中的选项并使用该新值运行特定任务。
最佳答案
问题:
根据您的问题和评论,我假设您的 Gruntfile.js
看起来像这样。
Gruntfile.js:
module.exports = function(grunt) {
grunt.initConfig({
dev_prod_switch: {
options: {
environment: grunt.option('env') || 'dev',
env_char: '#',
env_block_dev: 'env:dev',
env_block_prod: 'env:prod'
},
all: {
files: {
'appCommon/config.js': 'appCommon/config.js',
}
}
},
});
grunt.registerTask('dist-flow', function () {
if (!grunt.option('env') ) {
grunt.option('env', 'prod');
console.log(grunt.option('env'));
}
grunt.registerTask('dist',['dev_prod_switch']);
grunt.task.run('distdev');
});
};
您的问题是您尝试在任务中设置option
,然后在initConfig
对象中将其读回。问题是,initConfig
在您的任务之前运行,因此当您的 dist-flow
任务运行时,environment
已经设置为默认值。
这一行:
environment: grunt.option('env') || 'dev',
在此行之前运行:
grunt.option('env', 'prod');
解决方案:
在您的任务中,您可以通过 grunt.config
访问您的配置选项,因此您可以像这样修改配置对象中的值。
grunt.config.data.dev_prod_switch.options.environment = grunt.option('env');
示例 Gruntfile.js:
module.exports = function(grunt) {
grunt.initConfig({
dev_prod_switch: {
options: {
environment: grunt.option('env') || 'dev',
env_char: '#',
env_block_dev: 'env:dev',
env_block_prod: 'env:prod'
},
all: {
files: {
'appCommon/config.js': 'appCommon/config.js',
}
}
},
});
grunt.registerTask('dist-flow', function () {
if (!grunt.option('env') ) {
grunt.option('env', 'prod');
console.log(grunt.option('env'));
grunt.config.data.dev_prod_switch.options.environment = grunt.option('env');
console.log(grunt.config.data.dev_prod_switch.options.environment);
}
grunt.registerTask('dist',['dev_prod_switch']);
grunt.task.run('distdev');
});
};
关于javascript - Grunt 设置任务选项并使用新值运行该任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28364419/