· Travis Rodgers · Programming · 3 min read
How To Run Gulp Tasks According To Environment: Production or Development
I had two reasons for the need to run gulp tasks according to environment:
- I wanted a sourcemap in development, but have it removed in production.
- I wanted to minify my style.css in production only.
So if this peaks your interest, here is how to easily do it:
Run Gulp Tasks According To Environment
Step 1: Install node-gulp-mode
In your terminal run the command: npm i gulp-mode
(or npm i gulp-mode --save-dev
to save as a dependency in your json file (recommended)).
Now require it at the top of your gulp file:
Step 2: Choosing Production or Development
So nothing has changed. Your gulp still runs normally.
But with our gulp-mode package, we can now tell specific tasks to only run on production or only run on development.
How does it know what environment we are on? Well, we tell it.
Here are my two examples, sourcemaps and minification.
Example 1: Disable sourcemaps on production
To do this I need to locate the sourcemaps code in my gulpfile:
And since I want this to happen only in development, I simply add mode.development
to my desired function:
Still, how does it know what is development and what is not?
Because you tell it when you run gulp by adding the suffix --development
or --production
.
So if you are doing a gulp build, then gulp build --development
; a gulp watch, then gulp watch --development
or gulp watch --production
. You get the point.
Example 2: Enable minification only on production
I wanted gulp to minify my style.css on production, not development.
Just as we did above, I took my minification code in my gulpfile:
and told it to run with production only with mode.production
In my instance, I can run gulp watch --development
up until I'm ready to FTP it over to my live site, which I will then run a gulp --production
.
Conclusion
And this is how to run gulp tasks according to environment. Let me know if you have any questions or have anything to add.