· Travis Rodgers · Programming  · 3 min read

How To Run Gulp Tasks According To Environment: Production or Development

Irecently redesigned my website and in doing so I wanted to really dig into the benefits of gulp and Sass in website development. I'm not new to gulp or Sass, using it regularly in the freelance work that I do, but often the gulp file, or gulp template, is pre-determined by another designer, developer, or agency. So in taking the time to rebuild my own site from scratch with gulp and Sass, I want to share specifically an easy way to run gulp tasks according to environment; whether production or development.

I had two reasons for the need to run gulp tasks according to environment:

  1. I wanted a sourcemap in development, but have it removed in production.
  2. 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:

gulp tasks according to environment require gulp mode

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:

gulp tasks according to environment sourcemaps

And since I want this to happen only in development, I simply add mode.development to my desired function:

gulp tasks according to environment sourcemaps development

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:

gulp tasks according to environment minify only on production

and told it to run with production only with mode.production

gulp tasks according to environment minify only on production 2

 

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.

    Share:

    Related Posts

    View All Posts »