I’m looking for a way to minify a code like this:
JavaScript
x
4
1
setTimeout(function() {
2
document.getElementById('test').innerText = 'Hello World!';
3
}, 1000);
4
To something like this (minus spaces and new lines):
JavaScript
1
6
1
(function(a,b){
2
a(function(){
3
b('test').innerText='Hello World!';
4
}, 1000);
5
})(setTimeout, document.getElementById)
6
using an automatic tool like UglifyJS or similar. From the documentation it doesn’t seem to be an option to do that.
EDIT: It’s quite common to see code like this:
JavaScript
1
4
1
(function (window, document, undefined) {
2
// code here
3
})(window, document);
4
This is done for performance and to make the code more minifier-friendly, so I’m wondering why this is not done on a deeper level.
Advertisement
Answer
Using uglify-js (tested it with version 3.14.5 but it should also work with version 2), you can use the --enclose
option:
JavaScript
1
2
1
npx uglify-js --mangle --enclose setTimeout,document:setTimeout,document test.js --output test2.js
2
Giving the following output:
JavaScript
1
2
1
(function(e,t){e(function(){t.getElementById("test").innerText="Hello World!"},1e3)})(setTimeout,document);
2
Unfortunately it cannot replace expressions like document.getElementById
.