dotenv-webpack: DefinePlugin and `dotenv-webpack` conflict

I use a shared webpack.config.js among projects and it uses the DefinePlugin to write some variables during build time - including process.env.NODE_ENV. I would also like to use dotenv-webpack so projects using the shared config can supply a .env for build time as well. If I use both plugins, however, I receive the error:

WARNING in DefinePlugin
Conflicting values for 'process.env'

I can make sure in DefinePlugin that process.env isn’t used - except in some cases I need to write process.env.NODE_ENV at build time.

Instead, it would be preferable that dotenv-webpack simply merge with an existing process.env from DefinePlugin and overwrite any conflicts within.

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 10
  • Comments: 20 (9 by maintainers)

Most upvoted comments

This is a pretty convoluted problem, anyone have any ideas in particular to address this?

I can try to get to the update proposed above maybe later this month. I have a lot of personal things going on so I can’t make any promises. Of course I’m always open to someone opening a PR themselves if they need it sooner.

ANY UPDATE Please…

When I need to use the variables in the .env file with the --env variable that comes with webpack, I don’t have a good way.

Now I have to write webapck env into process.env first and then enable systemvars, But I don’t think it’s appropriate.

I want the following:

// execute npm run serve -- --env custom=1

// webpack.conf.js

module.exports = (env) => {
  console.log(env.custom) // 1
  return {
    plugins: [
      new DotenvPlugin({
        // I would like to have a configuration like this
        // It takes precedence over configuration in process.env and configuration in .env
        extralEnv: {...env}
      })
    ]
  }
}

Found this solution and it seemed to work for me, no more conflicting values for process.env https://stackoverflow.com/questions/67431401/conflicting-values-for-process-env-with-webpack-encore-and-dotenv

I just opened a PR #497. Would you mind taking a look and seeing if something like that would help in your scenario?

The idea is you would add { force: true } in your config object to make sure your variables take precedence over anything that pre-exists.

Perhaps:

new webpack.DefinePlugin({
  'process.env.something': '"true"',
  ...(new DotenvPlugin().definitions)
})

To simply spread the results? I’m not at my computer so not sure if this is totally accurate but hopefully you can follow what I’m thinking.