You can define a plugin in your webpack configuration. In your configuration, you'll want to add a plugin like this:
module.exports = {
plugins: [
new webpack.DefinePlugin({
__DEV__: JSON.stringify(JSON.parse(process.env.BUILD_DEV || 'true'))
})
]
}
By doing this, you'll replace all references to __DEV__
with the value of the BUILD_DEV
env var.
Since you'll likely already have NODE_ENV
set when building with webpack, you can take advantage of that. Here's another way using NODE_ENV
:
module.exports = {
plugins: [
new webpack.DefinePlugin({
__DEV__: process.env.NODE_ENV !== 'production'
})
]
}
As @Felix Kling mentioned in a comment, you can also use this technique to define multiple feature flags as seen here: https://github.com/petehunt/webpack-howto#6-feature-flags
If you make a build where NODE_ENV=production
, you'll have dead code. I believe this dead code is removed when you run your minification tool. See here: https://medium.com/@roman01la/dead-code-elimination-and-tree-shaking-in-javascript-build-systems-fb8512c86edf