Knowledge.ToString()

How To Use UglifyJS Conditional Compilation With reduce_vars

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 in February, 2019 and in UglifyJS 3.9.4 in June, 2020

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]/,passes=2 --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. In above command passes=2 is not needed for simple JavaScript file but may be required for complex file.

Share

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *