react-webpack-generators / generator-react-webpack

Yeoman generator for ReactJS and Webpack
http://newtriks.com/2013/12/31/automating-react-with-yeoman-and-grunt/
MIT License
2.88k stars 355 forks source link

env variables not passed through #260

Closed cheshire137 closed 8 years ago

cheshire137 commented 8 years ago

I'm trying to modify src/config/base.js to include an environment variable value like so:

export default {
  auth: {
    id: process.env.CLIENT_ID
  }
}

However, id is always undefined. I can console.log(process.env); in server.js and I see the CLIENT_ID environment variable as expected. So something strips it out before it makes it to the app, thus I'm not sure where configuration should live.

sthzg commented 8 years ago

hi @cheshire137 I do this by using Webpack's DefinePlugin to pass selected system variables through.

In the current generator version (the config system is refactored for the upcoming V4 release) you will have to modify these files:

Search for the plugins array (the above links are linked to the line numbers in the current release) and add or modify the DefinePlugin() entry to include a key/value of 'process.env.CLIENT_ID': JSON.stringify(process.env.CLIENT_ID):

new webpack.DefinePlugin({
  'process.env.CLIENT_ID': JSON.stringify(process.env.CLIENT_ID)
}),

cfg/dev.js for example might look like:

plugins: [
  new webpack.HotModuleReplacementPlugin(),
  new webpack.NoErrorsPlugin(),
  new webpack.DefinePlugin({
    'process.env.CLIENT_ID': JSON.stringify(process.env.CLIENT_ID)
  }),
  new BowerWebpackPlugin({
    searchResolveModulesDirectories: false
  })
],

cfg/dist.js like:

  plugins: [
    // ...
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': '"production"',
      'process.env.CLIENT_ID': JSON.stringify(process.env.CLIENT_ID)
    }),
    // ...
  ],

cfg/test.js like (this file will also need a let webpack = require('webpack'); at the top)

plugins: [
    new BowerWebpackPlugin({
      searchResolveModulesDirectories: false
    }),
    new webpack.DefinePlugin({
      'process.env.CLIENT_ID': JSON.stringify(process.env.CLIENT_ID)
    })
  ]

This way, Webpack exposes the system's env value for a specific key to the code that is transpiled into a bundle. Thus your reference in src/config/base.js should no longer be undefined, but use the value of process.env.CLIENT_ID.

sthzg commented 8 years ago

@cheshire137 I will close this issue due to inactivity, feel free to re-open it anytime if you have further questions.