Envifying javascript
Envifying is a simple and often misunderstood tool to create custom builds based on a predefined variable.
How envifying works
Envifying is the process of replacing this:
if(node.process.env === "production")
Into this:
if("production" === "production")
This is done based on a predefined variable set on your build process, in this case we’re using node.process.env
but we could be using any other custom variable.
So let’s say you want to conditionally load a module based on your environment config:
if (node.process.env === "production") {
const test = require('./test.prod');
} else {
const test = require('./test.dev');
}
Your build config would then set the environment variable based on your preferences. In this case let’s set production
as the value of node.process.env
if ("production" === "production") {
const test = require('./test.prod');
} else {
const test = require('./test.dev');
}
When used with a good minifier, your production ready code would then look like:
const test = require('./test.prod');
Because the expression created would always evaluate to true
a good minifier will be able to strip you’re code out of the unreachable parts and leave it clean without any conditional checks.
That’s why libraries like React are much faster when properly envifyed and minified even on the server side. Lot’s of error checks that are done to provide a great developer experience, are completely stripped out by this process leaving you with a much cleaner and faster build.
Webpack
In webpack you can achieve this with two plugins:
new webpack.DefinePlugin({
'process.env': { NODE_ENV: JSON.stringify('production') }
}),new webpack.optimize.UglifyJsPlugin()
You can use this not just for development
vs production
builds but also for for any other parameters that you choose to integrate into your build.