Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

javascript - Set gulp tasks depending on NODE_ENV

Is there a way to specify a gulp task depending on the NODE_ENV that is set?

For example in my package.json file, I have something like:

"scripts": {
    "start": "gulp"
 }

And I have multiple gulp tasks

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using a single ternary in your default gulp task, you can have something like:

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:

NODE_ENV=production npm start

Any other value of your NODE_ENV variable will launch the development task.


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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...