Bob Bob - 2 months ago 47
Node.js Question

How to pass process.env.NODE_ENV from Gulp to Webpack?

I have a gulpfile, where I create a webpackDevServer to live-update my js code. I set a

process.env.NODE_ENV
variable in gulpfile, but for some reason webpack doesn't see it - it is undefined.

Here's the relevant piece of my
gulpfile.js
:

gulp.task("watch", ["_set-env:dev"], function() {
// modify default webpack configuration for Development Server
var webpackDevConfig = Object.create(webpackConfig);
webpackDevConfig.devtool = "eval";
webpackDevConfig.debug = "true";

new webpackDevServer(webpack(webpackDevConfig), {
proxy: {
"/api/*": {target: "http://localhost:8000", secure: false},
"/static/*": {target: "http://localhost:8000", secure: false},
"/media/*": {target: "http://localhost:8000", secure: false}
}
}).listen(8001, "localhost", function (err) {
if (err) throw new gutil.PluginError("webpack-dev-server", err);
gutil.log("[webpack-dev-server]", "http://localhost:8001" + webpackDevConfig.output.publicPath);
});
});

gulp.task("_set-env:dev", function() {
gutil.log("set-env", "ENV => development");
genv({
vars: {
NODE_ENV: "development"
}
});
});


Then in webpack I check its value and it is undefined:

const webpack = require("webpack");
const path = require("path");

const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
...
const environmentsFile = path.join(__dirname, "/environments.json");
const nodeModulesPath = path.join(__dirname, "/node_modules");
const bowerComponentsPath = path.join(__dirname, "/bower_components");

console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
console.log(process.env.NODE_ENV);

const webpackConfig = {
entry: {
app: ["app.js"]
},


And on the console I see:

$ gulp watch
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
undefined
[22:28:34] Using gulpfile ~/Documents/frontend/gulpfile.js
[22:28:34] Starting '_set-env:dev'...
[22:28:34] set-env ENV => development
[22:28:34] Finished '_set-env:dev' after 7.63 ms
[22:28:34] Starting 'watch'...

Answer

You probably have something like this close to the top of your gulpfile:

var webpackConfig = require('./webpack.config.js');

That means your webpack configuration is evaluated before the _set-env:dev task even runs. Remember: your gulpfile only defines tasks. The tasks themselves aren't run until after the entire gulpfile has been evaluated.

You need to defer requiring your webpack configuration until after the _set-env:dev task has run by deleting the line at the top of your gulpfile and putting the require() directly into your watch task:

gulp.task("watch", ["_set-env:dev"], function() {
    // modify default webpack configuration for Development Server
    var webpackDevConfig = Object.create(require('./webpack.config.js'));