React-app-rewired: webpack.DefinePlugin not working

Created on 1 Nov 2017  路  7Comments  路  Source: timarney/react-app-rewired

Tried to do

config.plugins.push(
    new webpack.DefinePlugin({
        myVar: 1
    })
  )

typeof myVar
undefined

Most helpful comment

Check out https://github.com/webpack/webpack/issues/2427#issuecomment-342428107

In which case, that should be:

    new webpack.DefinePlugin({
        myVar: JSON.stringify(1),
    })

All 7 comments

Also i tried Object.assign iterating config.plugins by definitions key and extending it

So after reading that I didn't understand how. Just process.env.myVar = 1?

Check out https://github.com/webpack/webpack/issues/2427#issuecomment-342428107

In which case, that should be:

    new webpack.DefinePlugin({
        myVar: JSON.stringify(1),
    })

Check out webpack/webpack#2427 (comment)

In which case, that should be:

    new webpack.DefinePlugin({
        myVar: JSON.stringify(1),
    })

It's best not to do this. CRA provides custom environment variables
https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables

@likun7981

I'm also facing the same problem. I also tried this:

    new webpack.DefinePlugin({
        REACT_APP_VAR: JSON.stringify('var value'),
    })

process.env.REACT_APP_VAR is empty and directly printing REACT_APP_VAR throws an exception: 'REACT_APP_ROOT' is not defined.

I found something weird. If I have something like this:

ReactDOM.render(
  <div>{REACT_APP_ROOT}</div>,
  document.getElementById('root'))

It renders a "var value" for a moment and then throws the prior exception immediately. It means CRA is firstly understand the variable and then something strange happens.

Reading through the react-scripts code env.js, the environment variables are being added to the key process.env i.e.

  // Stringify all values so we can feed into Webpack DefinePlugin
  const stringified = {
    'process.env': Object.keys(raw).reduce((env, key) => {
      env[key] = JSON.stringify(raw[key]);
      return env;
    }, {}),
  };

Because you defining these using your own definition of `webpack.DefinePlugin and not using the official cra method for adding custom environment variables, you will need to define as follows:

    new webpack.DefinePlugin({
        "process.env.MY_CUSTOM_VAR": "Custom Value",
    })
Was this page helpful?
0 / 5 - 0 ratings