javascriptminifyclient-sideuglifyjs

uglify.js, browser version returns "is not a function"


Using the uglify.js browser-version, as mentioned here, on the first comment of the OP & getting this error in Chrome console: "UglifyJS.minify is not a function at FileReader."

The code used:

<!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>

Whatever is wrong with this code?


Solution

  • minify does not appear to be a function. See the instructions for the code you are using here: https://lisperator.net/uglifyjs/mangle.

    Replace UglifyJS.minify(e.target.result).code; with the below and you should get the result you want.

    let ast = UglifyJS.parse(code);
    
    // compressor needs figure_out_scope too
    ast.figure_out_scope();
    let 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 :)
    let code = ast.print_to_string();