[英]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.使用像 UglifyJS 或类似的自动工具。 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:使用uglify-js (用 3.14.5 版测试过,但它也适用于版本 2),您可以使用
--enclose
选项:
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
.不幸的是,它不能替换像
document.getElementById
这样的表达式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.