question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

DefinePlugin does not inject variable

See original GitHub issue

I have been trying to figure this out for over an hour now. Here is the subject code:

const ENVIRONMENT = process.env.NODE_ENV;
const BASENAME = process.env.APP_BASENAME;

console.log('process.env', {
    ENVIRONMENT: ENVIRONMENT,
    'process.env': process.env,
    NODE_ENV: process.env.NODE_ENV,
    APP_BASENAME: process.env.APP_BASENAME
});

if (ENVIRONMENT !== 'development' && ENVIRONMENT !== 'production') {
    throw new Error('Unknown ENVIRONMENT.');
}

export {
    BASENAME,
    ENVIRONMENT
};

Here is my webpack config:

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

module.exports = {
    devtool: 'source-map',
    debug: false,
    context: __dirname,
    entry: {
        'app': [
            path.resolve(__dirname, './src/app')
        ]
    },
    output: {
        path: path.resolve(__dirname, './dist'),
        filename: '[name].js',
        publicPath: '/static/'
    },
    plugins: [
        new webpack.optimize.UglifyJsPlugin({
            compressor: {
                /* eslint-disable camelcase */
                screw_ie8: true,
                /* eslint-enable */
                warnings: false
            }
        }),
        new webpack.DefinePlugin({
            'process.env.NODE_ENV': '"production"',
            'process.env.APP_BASENAME': '"' + (process.env.APP_BASENAME || '') + '"'
        }),
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: '"production"',
                APP_BASENAME: '"' + (process.env.APP_BASENAME || '') + '"'
            }
        }),
        new webpack.optimize.OccurrenceOrderPlugin(),
        new webpack.optimize.DedupePlugin(),
        new webpack.NoErrorsPlugin()
    ],
    module: {
        loaders: [
            {
                include: path.resolve(__dirname, './src'),
                loader: 'babel',
                test: /\.js$/,
            },
            {
                loaders: [
                    'style?sourceMap',
                    'css?modules&importLoaders=1&localIdentName=[name]___[local]___[hash:base64:5]',
                    'resolve-url',
                    'sass?sourceMap'
                ],
                test: /\.scss$/
            }
        ]
    }
};

As you can see, I have tried multiple methods of using DefinePlugin:

new webpack.DefinePlugin({
    'process.env.NODE_ENV': '"production"',
    'process.env.APP_BASENAME': '"' + (process.env.APP_BASENAME || '') + '"'
}),
new webpack.DefinePlugin({
    'process.env': {
        NODE_ENV: '"production"',
        APP_BASENAME: '"' + (process.env.APP_BASENAME || '') + '"'
    }
}),

Here is the console output:

{
    APP_BASENAME: "/campaign-master/upload-static",
    ENVIRONMENT: undefined,
    NODE_ENV: undefined,
    process.env: {
        APP_BASENAME: "/campaign-master/upload-static",
        NODE_ENV: "production"
    }
}

The script execution ends with an exception:

Uncaught Error: Unknown ENVIRONMENT.

As a result of the condition that you can see in the config.js.

What is the reason process.env.NODE_ENV is not getting replaced?

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Reactions:21
  • Comments:33 (4 by maintainers)

github_iconTop GitHub Comments

112reactions
amackintoshcommented, Nov 7, 2017

Hmm, I was just having this issue and it was trolling me. process.env was showing as an empty object, but after I read this https://github.com/webpack/webpack/issues/868 I tried explicitly calling process.env.NODE_ENV and process.env.APP_VERSION, and boom it worked fine. Watchout for that. It could be some of yours’ problems…

    new webpack.DefinePlugin({
        'process.env.NODE_ENV': JSON.stringify('development'),
        'process.env.APP_VERSION': JSON.stringify(process.env.npm_package_version),
    })

Inside some module:

console.log(process.env.APP_VERSION) === 0.0.1

console.log(process.env) === {}

63reactions
doncecommented, Apr 9, 2018

@amackintosh This is because DefinePlugin doesn’t build any object - it just replaces all occurrences of process.env.NODE_ENV in code with the constant you provided. In short, this works like find-and-replace variable with value 😃

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to inject Webpack DefinePlugin variables in non Module ...
This script is standard javascript (not a module), using one of the variables defined in DefinePlugin. It's a .js that must be loaded...
Read more >
DefinePlugin | webpack
The DefinePlugin replaces variables in your code with other values or expressions at compile time. This can be useful for allowing different behavior ......
Read more >
Environment Variables : Webpack config using DefinePlugin
In simple terms, Environment Variables are variables that are set depending on the computer (server) the software is running on.
Read more >
Environment Variables - SurviveJS
webpack.EnvironmentPlugin(["NODE_ENV"]) is a shortcut that allows you to refer to environment variables. It uses DefinePlugin underneath, and you can ...
Read more >
Vue.js, global variables and TypeScript - e0ne's comments
DefinePlugin injects a global variable into your JavaScript application. You may need it for some feature flags or some global configuration. Do not...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found