webpack配置里面拆出来单独使用uglify-es和uglify-js
因为别人写的代码会有很多全局的变量,所以不能用webpack打包,webpack打包会把全局的变量变成局部变量。所以我用uglify-es和uglify-js对项目的js进行压缩。
命令行
shell脚本
uglifyjs example.js -c -m -o dist/example.min.js
http://www.ruanyifeng.com/blog/2016/10/npm_scripts.html
uglify-es
https://github.com/mishoo/UglifyJS2
配置写在
config/index.js 文件夹里面
执行的是 node 命令
var UglifyJS = require("uglify-es"); var fs =require("fs"); var code = { "file1.js": "function add(first, second) { return first + second; }", "file2.js": "console.log(add(1 + 2, 3 + 4));" }; var options = { mangle: { toplevel: false, //不修改全局的变量名 }, nameCache: {} }; for(var codeI in code){ var true_code = code[codeI]; var result = UglifyJS.minify(true_code, options); fs.writeFile('./dist/'+codeI, result.code, function(err) { }); }
package.json里面写
"scripts": { "test": "echo "Error: no test specified" && exit 1", "start": "node config/index.js" },
npm run start可以执行压缩并且生成文件
优化输入,自动读取输入文件
var UglifyJS = require("uglify-es"); var fs = require("fs"); var conFig = { enterFile: 'files/', outFile: './dist' } deleteDist(); var code = {} fs.readdirSync('files').map((file) => { console.log(file); var content = fs.readFile(conFig.enterFile+file,'utf-8', function (err,data) { code = {}; code[file] = data; Uglify(code) }); }); function deleteDist(){ fs.readdirSync(conFig.outFile).map((file) => { fs.unlink(conFig.outFile+`/${file}`,(err) => { if (err) { console.log(err); } else { console.log('delete ok'); } }); }); } function Uglify(code) { var options = { mangle: { toplevel: true, }, nameCache: {} }; for(var codeI in code){ var true_code = code[codeI]; var result = UglifyJS.minify(true_code, options); fs.writeFile(conFig.outFile+'/'+codeI, result.code, function(err) { }); } }