如何 minify/uglify 记录和 window 属性和方法

How to minify/uglify document and window properties and methods

我正在寻找一种方法来缩小这样的代码:

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

像这样(减去空格和换行):

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

使用像 UglifyJS 或类似的自动工具。 从文档来看,这似乎不是一个选项。

编辑: 看到这样的代码很常见:

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

这是为 performance and to make the code more minifier-friendly 完成的,所以我想知道为什么没有在更深层次上完成。

您可以使用 task runner,或 module bundlercommand line :

以及其他几个工具。

使用 uglify-js(用 3.14.5 版本测试过,但它应该也适用于版本 2),你可以使用 --enclose 选项:

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

给出以下输出:

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

遗憾的是,它无法替换 document.getElementById.

等表达式