問題描述
有沒有辦法根據設置的 NODE_ENV
指定 gulp 任務?
Is there a way to specify a gulp task depending on the NODE_ENV
that is set?
例如在我的 package.json
文件中,我有類似的內容:
For example in my package.json
file, I have something like:
"scripts": {
"start": "gulp"
}
我有多個 gulp
任務
gulp.task('development', function () {
// run dev related tasks like watch
});
gulp.task('production', function () {
// run prod related tasks
});
如果我設置NODE_ENV=production npm start
,我可以指定只運行gulp production
嗎?或者有更好的方法嗎?
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?
推薦答案
在你的默認 gulp 任務中使用一個三元組,你可以有類似的東西:
Using a single ternary in your default gulp task, you can have something like:
gulp.task('default',
[process.env.NODE_ENV === 'production' ? 'production' : 'development']
);
然后您將能夠在您的 package.json
中保留單個 gulp
命令并像您所說的那樣使用它:
You will then be able to keep the single gulp
command in your package.json
and using this like you said:
NODE_ENV=production npm start
NODE_ENV
變量的任何其他值都將啟動 development
任務.
Any other value of your NODE_ENV
variable will launch the development
task.
您當然可以使用允許多個任務的對象進行高級用法并避免 if
樹地獄:
You could of course do an advanced usage using an object allowing for multiple tasks and avoiding if
trees hell:
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.
這篇關于根據 NODE_ENV 設置 gulp 任務的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!