Environment Variables in an isomorphic JS app: Webpack find & replace?
javascript, webpack
Solution
In your `webpack.config.js`, use the following `preLoaders` (or `postLoaders`),
module: {
preLoaders: [
{ test: /\.js$/, loader: "transform?envify" },
]
}
Another way using the `webpack.DefinePlugin`:
plugins: [
new DefinePlugin({
'process.env': Object.keys(process.env).reduce(function(o, k) {
o[k] = JSON.stringify(process.env[k]);
return o;
}, {})
})
]
NOTE: The old method using `envify-loader` was deprecated:
DEPRECATED: use transform-loader + envify instead.
Problem
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]; }) ```