Jophin Joseph
Jophin Joseph

Reputation: 2953

Injecting an environment variable from gulp to webpack

I have a gulpfile from which I'm initiating webpack bundling. The webpack configuration has an alias defined that uses process.env.NODE_ENV as shown below

.
.
resolve: {
    modulesDirectories: ["node_modules", "js", "jsx"],
    extensions: ["", ".js", ".jsx"],
    alias: {
        config: path.join(__dirname, ('config.' + process.env.NODE_ENV + '.js'))
    }
}..

In the gulpfile, I have 2 tasks that execute in sequence

  1. set-env that sets the environment variable using gulp-env as follows

    gulpEnv({
        vars: {
            NODE_ENV: 'dev'
        }
    });
    
  2. webpack task that depends on the previous task and executes only when the first is completed

Here the variable is not getting injected properly it seems. The file name is getting resolved as config.undefined.js. Is there something wrong with what I'm doing?

Upvotes: 3

Views: 808

Answers (1)

Jophin Joseph
Jophin Joseph

Reputation: 2953

I changed my approach it to something like this

Webpack

var NODE_ENV = process.env.NODE_ENV;

var config = {
    .
    .
    resolve: {
        modulesDirectories: ["node_modules", "js", "jsx"],
        extensions: ["", ".js", ".jsx"],
        alias: {
            //<envt> will be injected by gulp
            config: config: path.join(__dirname, ('config.<envt>.js'))
        }
    }
    .
    .
    .
}

//If webpack is directly invoked with NODE_ENV, replacement will happen here
if (NODE_ENV) {
    config['resolve']['alias']['config'] = config['resolve']['alias']['config'].replace(/<envt>/, NODE_ENV);
}

module.exports = config;

Gulp

  1. Inside set-env instead of setting using gulp-env, I simply set a global variable NODE_ENV='dev'
  2. Inside webpack task, I'm doing webpackConfig['resolve']['alias']['config'] = webpackConfig['resolve']['alias']['config'].replace(/<envt>/, NODE_ENV);

This worked for me

Upvotes: 1

Related Questions