简体   繁体   中英

How to minify/uglify document and window properties and methods

I'm looking for a way to minify a code like this:

setTimeout(function() {
  document.getElementById('test').innerText = 'Hello World!';
}, 1000);

To something like this (minus spaces and new lines):

(function(a,b){
  a(function(){
    b('test').innerText='Hello World!';
  }, 1000);
})(setTimeout, document.getElementById)

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:

(function (window, document, undefined) {
  // code here
})(window, document);

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.

You can use a task runner , or module bundler or command line to this:

And several other tools.

Using uglify-js (tested it with version 3.14.5 but it shoudl also work with version 2), you can use the --enclose option:

npx uglify-js --mangle --enclose setTimeout,document:setTimeout,document test.js --output test2.js

Giving the following output:

(function(e,t){e(function(){t.getElementById("test").innerText="Hello World!"},1e3)})(setTimeout,document);

Unfortunately it cannot replace expressions like document.getElementById .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM