Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Environment Variables in an isomorphic JS app: Webpack find & replace?

I'm using webpack to bundle an isomorphic JS app (based on this example) so that the browser runs the same code as the server. Everything is running smoothly except I have a config.js with some settings which are pulled in from environment variables on the server:

module.exports = {
  servers:
    auth: process.env.AUTH_SERVER_URL,
    content: process.env.CONTENT_SERVER_URL
  }
}

On the server this is grand, but when webpack renders this for the client process is empty and this doesn't work.

I'm hoping there's a kind of 'find and replace' webpack plugin that will replace them with their content in that file alone?

"…config.js content…".replace(/process\.env\.([a-z0-9_]+)/, function(match, varName) {
  return process.env[varName];
})
like image 430
JP. Avatar asked Feb 25 '15 11:02

JP.


1 Answers

Note that using the DefinePlugin as suggested in the accepted answer is potentially a dangerous action as it completely exposes process.env. As Tobias commented above there's actually a plugin EnvironmentPlugin that does exactly this with an added whitelisting ability, using DefinePlugin internally.

In your webpack.config.js:

{
  plugins: [
    new webpack.EnvironmentPlugin([
      'NODE_ENV',
      'WHITELISTED_ENVIRONMENT_VARIABLE'
    ])
  ]
}
like image 199
owerme Avatar answered Oct 13 '22 07:10

owerme