How to use UglifyJS conditional compilation with reduce_vars

By | May 20, 2019 | 0 Comment
Category: Javascript Tags:

UglifyJS supports conditional compilation using the “–define” argument. Even though this option is good enough, it “looks” messy. The command prompt argument becomes too long and making an addition to the constant feels dreaded. Here is a quick way to use separate js file to define all your constants and use it in subsequent files.

UglifyJS provides an option “reduce_vars” but it does not work with the default settings. I was pulling my hair trying to figure out why it was not working as expected. Searching over the Internet could not help. Here is a working sample.

Note: This code is tested in UglifyJS 3.5

defines.js File Content

var DEBUG = true;
var MYCONST = true;

test.js File Content

if(DEBUG) {
alert(“in debug”);
} else {
alert(“not in debug”);
var myObject = {};

Here is the working command that will remove the constants and also unused code

uglifyjs “defines.js” “test.js” –compress toplevel=true,top_retain=/^[a-z]/ –output “build.min.js”

Here the important parameter is “toplevel” and “top_retain”. Without “toplevel=true”, constants and conditional code will not be removed. If you provide “toplevel=true”, all the top level functions and variables will be removed because those are considered “unused”. The solution is to provide “top_retain” value. Here I am telling UglifyJS to retain only those variables and functions intact if they start with lowercase. You may need to update the “top_retain” value based on your need.

About Vishal Monpara

Vishal Monpara is a full stack Solution Developer/Architect with 13 years of experience primarily using Microsoft stack. He is currently working in Retail industry and moving 1's and 0's from geographically dispersed hard disks to geographically dispersed user leveraging geographically dispersed team members.