javascript 根据 NODE_ENV 设置吞咽任务
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29223471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set gulp tasks depending on NODE_ENV
提问by cusejuice
Is there a way to specify a gulp task depending on the NODE_ENV
that is set?
有没有办法根据NODE_ENV
设置的来指定 gulp 任务?
For example in my package.json
file, I have something like:
例如在我的package.json
文件中,我有类似的东西:
"scripts": {
"start": "gulp"
}
And I have multiple gulp
tasks
我有多项gulp
任务
gulp.task('development', function () {
// run dev related tasks like watch
});
gulp.task('production', function () {
// run prod related tasks
});
If I set NODE_ENV=production npm start
, can I specify to only run gulp production
? Or is there a better way to do this?
如果我设置NODE_ENV=production npm start
,我可以指定只运行gulp production
吗?或者有没有更好的方法来做到这一点?
回答by Balthazar
Using a single ternary in your default gulp task, you can have something like:
在默认的 gulp 任务中使用单个三元组,您可以使用以下内容:
gulp.task('default',
[process.env.NODE_ENV === 'production' ? 'production' : 'development']
);
You will then be able to keep the single gulp
command in your package.json
and using this like you said:
然后,您将能够保留单个gulp
命令package.json
并像您说的那样使用它:
NODE_ENV=production npm start
Any other value of your NODE_ENV
variable will launch the development
task.
NODE_ENV
变量的任何其他值都将启动development
任务。
You could of course do an advanced usage using an object allowing for multiple tasks and avoiding if
trees hell:
您当然可以使用允许多个任务并避免if
树地狱的对象进行高级用法:
var tasks = {
development: 'development',
production: ['git', 'build', 'publish'],
preprod: ['build:preprod', 'publish:preprod'],
...
}
gulp.task('default', tasks[process.env.NODE_ENV] || 'fallback')
Keep in mind that when giving an array of tasks, they will be run in parallel.
请记住,当提供一系列任务时,它们将并行运行。
回答by mwotton
Have your first gulp task run other gulp tasks based on the process.env.NODE_ENV
value.
让您的第一个 gulp 任务根据该process.env.NODE_ENV
值运行其他 gulp 任务。
gulp.task('launcher', function(){
switch (process.env.NODE_ENV){
case 'development':
// Run dev tasks from here
break;
case 'production':
// Run prod tasks
break;
}
});
回答by Mukesh Rawat
The other simple way could be
另一种简单的方法可能是
gulp.task('set-dev-env', function () {
return process.env.NODE_ENV = 'development';
});
gulp.task('set-prod-env', function () {
return process.env.NODE_ENV = 'production';
});
gulp.task('development', ['set-dev-env'], function () {
// your code
});
gulp.task('production', ['set-prod-env'], function () {
// your code
});
Run gulp production
or gulp development
.
运行gulp production
或gulp development
。
回答by Michael Blankenship
if (process.env.NODE_ENV === "production")
// whatever