使用 uglify.js 浏览器版本,如here所述,在 OP 的第一条评论中并在 Chrome 控制台中出现此错误:“UglifyJS.minify 不是 FileReader 的函数。”
使用的代码:
<!DOCTYPE html>
<html>
<head>
<script src="https://lisperator.net/s/js/uglifyjs/uglify.js"></script>
<style>
#drop_zone{
width: 300px;
height: 300px;
border: 2px dashed #bbb;
text-align: center;
padding: 5px;
}
</style>
</head>
<body>
<div id="drop_zone">
<span>Drag and drop HTML files to minify</span>
</div>
<script>
console.log(UglifyJS);
var filesAr = [],
dz = document.getElementById('drop_zone');
function handleFileSelect(evt) {
evt.stopPropagation();
evt.preventDefault();
var files = evt.dataTransfer.files;
for (var i = 0, f; f = files[i]; i++) {
var reader = new FileReader();
reader.onload = (function(file) {
return function(e) {
var minfd = UglifyJS.minify(e.target.result).code;
filesAr.push({name: file.name, min: minfd});
};
})(f);
reader.readAsText(f);
}
console.log(filesAr);
}
function handleDragOver(evt) {
evt.stopPropagation();
evt.preventDefault();
evt.dataTransfer.dropEffect = 'copy';
}
dz.addEventListener('dragover', handleDragOver, false);
dz.addEventListener('drop', handleFileSelect, false);
</script>
</body>
</html>
这段代码有什么问题吗?
minify 似乎不是一个函数。请参阅此处使用的代码说明:https://lisperator.net/uglifyjs/mangle.
用下面的替换
UglifyJS.minify(e.target.result).code;
,你应该得到你想要的结果。
ast = UglifyJS.parse(code);
// compressor needs figure_out_scope too
ast.figure_out_scope();
compressor = UglifyJS.Compressor()
ast = ast.transform(compressor);
// need to figure out scope again so mangler works optimally
ast.figure_out_scope();
ast.compute_char_frequency();
ast.mangle_names();
// get Ugly code back :)
code = ast.print_to_string();