When setting environment variables for Gulp tasks, several approaches can be used. Environment variables allow you to use different configurations across various development stages (such as development, testing, and production) without modifying the code itself. Here are several methods for setting and using environment variables in Gulp tasks:
Method 1: Using process.env
In Node.js, the process.env object contains information about the system environment. You can directly reference these environment variables within Gulp tasks.
Example:
Suppose you want to minify or not minify JS files based on different environments (development or production). You can set environment variables in the command line and read them in your Gulp file:
bashexport NODE_ENV=production
javascriptconst gulp = require('gulp'); const uglify = require('gulp-uglify'); const gulpif = require('gulp-if'); gulp.task('scripts', function() { return gulp.src('src/js/**/*.js') .pipe(gulpif(process.env.NODE_ENV === 'production', uglify())) .pipe(gulp.dest('dist/js')); });
In this example, JS files will only be minified when the NODE_ENV environment variable is set to production.
Method 2: Using third-party libraries like dotenv
If your project has many environment variables or requires better management, using the dotenv library can conveniently manage these variables. First, you need to install dotenv in your project.
bashnpm install dotenv
Then, you can create a .env file in the project root directory and set environment variables inside it:
shellNODE_ENV=production API_KEY=some-api-key
In your Gulp file, you can use them as follows:
javascriptrequire('dotenv').config(); const gulp = require('gulp'); const uglify = require('gulp-uglify'); const gulpif = require('gulp-if'); gulp.task('scripts', function() { console.log('Environment:', process.env.NODE_ENV); console.log('API Key:', process.env.API_KEY); return gulp.src('src/js/**/*.js') .pipe(gulpif(process.env.NODE_ENV === 'production', uglify())) .pipe(gulp.dest('dist/js')); });
This approach makes environment variable management more centralized and systematic, and it also facilitates switching configurations across different environments.
Here are several methods for setting and using environment variables in Gulp tasks. This helps you automatically adjust task behavior based on different environments, making the build process more flexible and configurable.