I saw an interesting question on Discord today about accessing process.env.NODE_ENV
for dead code elimination with Uglify.
Background
A little background for those who are not familiar with this.
var setting = process.env.NODE_ENV === "production" ? "production" : "development"
Combines with webpack DefinePlugin or browserify envify plugin, the snippet above will be turned into
var setting = "production" === "production" ? "production" : "development"
and uglify will applies its magics to turn it into
var setting = "production"
Bucklescript
How to do that in Bucklescript then?
First, binding:
[@bs.val] external env : string = "process.env.NODE_ENV";
Usage:
let settings =
if (env == "production") {
"production";
} else {
"development";
};
Some notes:
- Do not extract
env == "production"
into a variable, uglify can’t deal with that - Do not use ternary
let settings = env == "production" ? "production" : "development";
The above ternary is desugared into a pattern matching expression like this
let settings =
match env = "production" with
| true -> "production"
| false -> "development"
Bucklescript turns it into
var match = +(process.env.NODE_ENV === "production");
var settings = match !== 0 ? "production" : "development";
Uglify can’t work with that either.