How to use the minify function from uglify-js

Find comprehensive JavaScript uglify-js.minify code examples handpicked from public code repositorys.

The uglify-js.minify function is used to compress and optimize JavaScript code.

94
95
96
97
98
99
100
101
102
103
		dash = "loadNgModules(" + templatePathArr[count] + " , " + controllerPathArr[count] + ", true)"
		count++
		return dash
	}))
} else {
	pluginContent = uglifyjs.minify(pluginContent)
}

if (manifest.renderer.dependencies) {
	manifest.renderer.dependencies.forEach(function (obj, i) {
fork icon76
star icon6
watch icon8

+ 56 other calls in file

363
364
365
366
367
368
369
370
371
372
payload += fs.readFileSync('./src/js/main.js')
ejs.renderFile('./src/tpl/mainjs.ejs',{payload: payload}, function(err, str) {
    if (err !== null) {
        console.log(err)
    }
    let res = uglify.minify(str)
    if (res.error !== undefined) {
        console.log('uglify', res.error)
    }
    fs.writeFileSync(outputPath+"/main.js", res.code)
fork icon0
star icon4
watch icon2

+ 4 other calls in file

How does uglify-js.minify work?

uglify-js.minify is a JavaScript minifier that reduces the size of JavaScript files by removing unnecessary characters such as whitespace, comments, and renaming variables with shorter names without affecting functionality. It uses a process called abstract syntax tree (AST) parsing to modify the code before it is compressed.

145
146
147
148
149
150
151
152
153
154
if(--tasksCount == 0) {
	var cacheFile = "public/"+type+"/cache-"+hash+"."+type;
	var code=fileBodies.join("\n");
	if(type=="js") {
		if(config.minifyScripts)
			code = uglify.minify(code,{fromString:true}).code;
	} else if(type=="css") {
		if(config.minifyStyles)
			code = new ccss({
				processImport: false,
fork icon2
star icon3
watch icon3

+ 39 other calls in file

29
30
31
32
33
34
35
36
37
38
39
    destPath = undefined;
  }
  if (!destPath) {
    destPath = srcPath.replace(/(?=\.js$)/, '.min');
  }
  const output = uglify.minify(srcPath, _.defaults(options || {}, uglifyOptions));
  fs.writeFile(destPath, output.code, 'utf-8', callback);
}


module.exports = minify;
fork icon0
star icon2
watch icon1

+ 104 other calls in file

Ai Example

1
2
3
4
5
6
7
8
const UglifyJS = require("uglify-js");

const code = "function add(a, b) { return a + b; }";
const options = { compress: true, mangle: true };

const minified = UglifyJS.minify(code, options);

console.log(minified.code); // "function add(n,d){return n+d}"

In this example, UglifyJS.minify() is used to minify the code string using the given options. The resulting minified object contains the minified code in its code property, which is then logged to the console.

60
61
62
63
64
65
66
67
68
69
        dash = 'loadNgModules(' + templatePathArr[count] + ' , ' + controllerPathArr[count] + ', true)'
        count++;
        return dash;
    }))
} else {
    pluginContent = uglifyjs.minify(pluginContent);
}

if (manifest.editor.dependencies) {
    manifest.editor.dependencies.forEach(function(obj, i) {
fork icon47
star icon1
watch icon8

+ 35 other calls in file

87
88
89
90
91
92
93
94
95
96
97
98
99
);






const minify = (fileName, newFileName) => {
    const minified = UglifyJS.minify(fs.readFileSync(path.join(__dirname, './client', fileName), 'utf8'));
    if (minified.error) {
        throw minified.error;
    }
    fs.writeFileSync(path.join(__dirname, './client', newFileName), minified.code, 'utf8');
fork icon0
star icon2
watch icon1

74
75
76
77
78
79
80
81
82
83
let code = fs.readFileSync(`${__dirname}/../../../${req.url}`, "utf-8");

if(loadedMinify.has(req.url)){ code = loadedMinify.get(req.url); }
else{
    if(req.url.endsWith(".js")){
        code = isDevMod ? code : uglifyjs.minify(code, {
            mangle: { keep_fnames: true }
        }).code;

        if(!Object.keys(req.query).includes("required")){
fork icon0
star icon2
watch icon1

+ 3 other calls in file

21
22
23
24
25
26
27
28
const unpackerUMD = code.replace("%", `exports.Unpacker = ${unpackerSliced}`);
const allUMD = code.replace("%", `exports.Packer = ${packerSliced}; exports.Unpacker = ${unpackerSliced}`);


mkdirSync("./umd", { recursive: true });
writeFileSync("./umd/packer.min.js", uglify.minify(packerUMD).code);
writeFileSync("./umd/unpacker.min.js", uglify.minify(unpackerUMD).code);
writeFileSync(`./umd/${packageName.toLowerCase()}.min.js`, uglify.minify(allUMD).code);
fork icon0
star icon2
watch icon1

+ 5 other calls in file

251
252
253
254
255
256
257
258
259
260
tim("navscript");
//navigation handler import
nav = dom.window.document.createElement("script");
let njs = fs.readFileSync(__dirname+"/nav.js", "utf-8");
if(config.minifyJS){
	njs = UglifyJS.minify(njs);
	if(njs.error != undefined){
		throw njs.error;
	}
	njs=njs.code;
fork icon11
star icon53
watch icon13

+ 79 other calls in file

4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
        drop_debugger,
        drop_console
    }
};

const result = UglifyJS.minify(conversion, {
    ...uglifyOptions
});

if (result.map)
fork icon0
star icon10
watch icon1

+ 2 other calls in file

295
296
297
298
299
300
301
302
303
304
 if (debug) {
     log(`\n\n【debug】===============这是 返回result==============`);
     log(data)
 }
if(result.success == true){
    token = uglifyjs.minify(result.token).code
   
    token = eval(uglifyjs.minify('window={};'+token).code)
    token = eval(key) 
    log('token:'+token)
fork icon0
star icon2
watch icon1

275
276
277
278
279
280
281
282
283
}

let reservedVars = _.range(1, 64).map(x => encodeBijective(BigInt(x), '_$'))

function encodeExpression(expr) {
  let code = uglify.minify(String(expr), {
    mangle: {reserved: reservedVars},
    compress: {reduce_funcs: true},
  }).code
fork icon0
star icon2
watch icon1

45
46
47
48
49
50
51
52
53
54
    var code = result.code.replace(
      /(sweetAlert.*?).version = ''/,
      `$1.version = '${pack.version}'`
    )
    if (options.minify) {
      code = uglify.minify(code).code
    }
    return write(options.dest, code)
  })
})
fork icon2
star icon0
watch icon1

429
430
431
432
433
434
435
436
437
438
    let result = JSON.parse(data);
    if (debug) {
        log(`\n\n【debug】===============这是 返回result==============`);
        log(data)
    }
    Tokens = uglifyjs.minify(result.data)



} catch (e) {
fork icon4
star icon0
watch icon1

+ 3 other calls in file

20
21
22
23
24
25
26
27
28
29
    name: 'Worker Loader',
    baseDataPath: 'options'
});
//丑化代码
if (options.uglify) {
    source = _uglify.minify(source, {
        mangle: {
            toplevel: true,
        },
        nameCache: {}
fork icon0
star icon1
watch icon1

+ 2 other calls in file

695
696
697
698
699
700
701
702
703
704
(value.parse || (value.parse = {})).bare_returns = false;
options.minifyJS = function(text, inline) {
  var start = text.match(/^\s*<!--.*/);
  var code = start ? text.slice(start[0].length).replace(/\n\s*-->\s*$/, '') : text;
  value.parse.bare_returns = inline;
  var result = UglifyJS.minify(code, value);
  if (result.error) {
    options.log(result.error);
    return text;
  }
fork icon0
star icon0
watch icon0

+ 28 other calls in file

210
211
212
213
214
215
216
217
218
219
220
221
222
}
`


fs.writeFileSync("./VS Code Extension/overpy.js", overpyCode);


var minifiedCode = UglifyJS.minify(overpyCode).code;
fs.writeFileSync("./VS Code Extension/overpy.min.js", minifiedCode);


//fs.writeFileSync("./bot/overpy.js", overpyCode);

fork icon0
star icon0
watch icon1

26
27
28
29
30
31
32
33
34
35
36
}


function uglifyCode(code) {
	return new Promise((resolve, reject)=>{
		try {
			const result = UglifyJS.minify(code, {
				output: 
					{
						ascii_only:true
					},
fork icon0
star icon0
watch icon1

242
243
244
245
246
247
248
249
250
251
 * 
 * @param {*} script 
 * @param {*} sourceMap 
 */
function obfuscate(script, sourceMap) {
    return uglify.minify(script, {
        nameCache: null, // or specify a name cache object
        toplevel: false,
        ie8: false,
        warnings: false,
fork icon0
star icon0
watch icon2

265
266
267
268
269
270
271
272
273
274
for (let lang of LANGUAGES) {
    for (let srcRelativePath of srcRelativePathList) {
        let srcAbsolutePath = path.resolve(projectDir, srcRelativePath);
        let content = fs.readFileSync(srcAbsolutePath, 'utf8');

        let result = uglify.minify(content);
        if (result.error) {
            console.log(chalk.red(srcAbsolutePath));
            console.error(result.error);
            process.exit(1);
fork icon0
star icon0
watch icon1