Webpack definePlugin not setting/reading node_env variable
Asked Answered
C

2

10

I'm having real issues injecting the node_env var into my code through Webpack's definePlugin and after reading numerous posts nothing seems to work. I have a feeling I'm missing something...

So my production webpack config is -

// Config
import path from 'path';
import webpack from 'webpack';
import config from './config';


/**
 * Webpack config for compiling the
 * React/Redux/ES6 scripts.
 *
 * ENV = production
 *
 * @type {Object}
 */
module.exports = {
    entry: path.resolve(__dirname, '../', config.assets.scripts.src_dir, config.assets.scripts.entry),
    devtool: false,
    output: {
        path: path.resolve(__dirname, config.assets.scripts.dist_dir),
        filename: config.assets.scripts.dist_min
    },
    module: {
        loaders: [
            {
                test: /.js?$/,
                loader: 'babel-loader?presets[]=react,presets[]=es2015,presets[]=stage-0',
                exclude: /node_modules/
            },
            {
                test: /\.json$/,
                loader: 'json-loader'
            }
        ]
    },
    plugins: [
        new webpack.DefinePlugin({
            'process.env': {
                'NODE_ENV': JSON.stringify('production')
            }
        }),
        new webpack.optimize.UglifyJsPlugin({})
    ]
};

I've tried setting alias's for react, react-dom and react-redux with absolutely no avail, React still warns me i'm using a minified version outside of node_env=production (Also redux still throws me this error).

FYI, i'm using webpack version 2.2.1.

Is it something to do with the babel-loader conflicting in some way? If anyone can point me in the right direction that would be great.

Caves answered 29/3, 2017 at 3:15 Comment(0)
D
11

Try changing your DefinePlugin for NODE_ENV to this one -

plugins: [
    new webpack.DefinePlugin({
        'process.env.NODE_ENV' : JSON.stringify('production')
    }),
    new webpack.optimize.UglifyJsPlugin({
        minimize : true,
        compress : {
            warnings : false
        }
    })
]
Dichroscope answered 29/3, 2017 at 7:7 Comment(2)
This did actually work (or at least I think it did as it seems to have cleared the error). Do you have any knowledge on why you must specific the object property like that? Is it a bug with Webpack? ThanksCaves
@Caves I think for more clarification you should read this thread github.com/webpack/webpack/issues/868 And if it did work for you then please accept the answer. thanksDichroscope
S
0

Now you can use the simpler EnvironmentPlugin

https://webpack.js.org/plugins/environment-plugin/

It's does exactly the same thing as DefinePlugin (when you're just forwarding environment variables) but with a much simpler syntax

e.g. new webpack.EnvironmentPlugin(['NODE_ENV'])

Sternick answered 12/6, 2024 at 21:30 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.