Webpack-encore: Document how to works with environment variables

Created on 16 Apr 2019  路  6Comments  路  Source: symfony/webpack-encore

Just a reminder to write a documentation for Encore.configureDefinePlugin(), and the integration with Symfony .env files and process.env.*.

Encore.configureDefinePlugin(options => {
  options['process.env'].MY_OPTION = JSON.stringify('foo');
});

For example for configuring sentry DNS from .env file:

Encore.configureDefinePlugin(options => {
  const env = dotenv.config();

  if (env.error) {
    throw env.error;
  }

  options['process.env'].SENTRY_DSN = JSON.stringify(env.parsed.SENTRY_DSN);
});

Most helpful comment

In fact, what about adding a new method like .injectEnvironmentVariables(['NODE_ENV', '...']) that will:

  • resolve environment variables like Symfony do
  • automatically inject them with DefinePlugin + JSON.stringify

?

It can be a bit hard to implement it properly, but it will be 100 times more user friendly

All 6 comments

We'll have to be careful about that one: there could be confusion related to the fact that it will be interpretated at build time and not on the server it'll be deployed to (like Symfony).

Yup, we should note that

In fact, what about adding a new method like .injectEnvironmentVariables(['NODE_ENV', '...']) that will:

  • resolve environment variables like Symfony do
  • automatically inject them with DefinePlugin + JSON.stringify

?

It can be a bit hard to implement it properly, but it will be 100 times more user friendly

What about this issue ? Would be very helpful ;)

A proposal has been opened on #568, but it's totally not an easy feature in fact :p

I start using https://www.npmjs.com/package/dotenv-webpack in my project.

After installation:

In webpack.config.js import it:

const Dotenv = require('dotenv-webpack');

Add it as plugin:

.addPlugin(new Dotenv( { path: './.env.local', systemvars: true } ))

start using it in code:

{process.env.npm_package_version}

@anaelChardan

Was this page helpful?
0 / 5 - 0 ratings