UglifyJS — JavaScript parser, compressor, minifier written in JS (original) (raw)
These pages are old. They apply to UglifyJS v2. Version 3 has evolved a lot in the mean time to support most of ES6. Please check the documentation in the official repository for up-to-date information. Big thanks to all contributors, especially to Alex Lam S.L., who has maintained this project for years!
UglifyJS is a JavaScript compressor/minifier written in JavaScript. It also contains tools that allow one to automate working with JavaScript code:
- A parser which produces an abstract syntax tree (AST) from JavaScript code.
- A code generator which outputs JavaScript code from an AST, also providing the option to get asource map.
- A compressor (optimizer) — it uses the transformer API to optimize an AST into a smaller one.
- A mangler — reduce names of local variables to (usually) single-letters.
- A scope analyzer, which is a tool that augments the AST with information about where variables are defined/referenced etc.
- A tree walker — a simple API allowing you to do something on every node in the AST.
- A tree transformer — another API intended to transform the tree.
All the above utilities and APIs are defined in ~6500 lines of code (except for the effective generation of the source-map, which is handled by the source-map module). Compared to alternatives, UglifyJS is pretty small.
These pages document the internals of UglifyJS. For a documentation of the command-line options please see the README.
Installing (for NodeJS)
You can install UglifyJS from NPM:
npm install uglify-js
but you can also use the Git repository if you feel adventurous:
git clone git://github.com/mishoo/UglifyJS2.git cd UglifyJS2 npm link .
Building for the browser
Once you installed it for NodeJS, UglifyJS2 provides a quick way to build itself for the browser:
uglifyjs --self -c -m -o /tmp/uglifyjs.js
Now you have it in /tmp/uglifyjs.js and can include that single file in a browser. If you need source maps you'll also have to include the Mozilla source-map module. details to be clarified
Exported API
UglifyJS is written in “classic style”, so to say — it's not using the CommonJS module system (I find it more of an annoyance than of real help, especially for prototyping/development). To load it in NodeJS there's a single file that needs to be require-d: tools/node.js. If you installed it with npm install or npm link as mentioned above, then this file is loaded when you say var UglifyJS = require("uglify-js2")
. This single file will load all the others in a separate execution context, so you should not worry about messing your global environment, and it returns a single object where all the global definitions in UglifyJS are exported.
Stats
Here are some stats showing where UglifyJS2 stands compared to other minifiers. Show charts.