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 addfirst, second) { return first + second; }", "file2.js": "console.logadd1 + 2, 3 + 4));" }; var options = { mangle: { toplevel: false, //不修改全局的变量名 }, nameCache: {} }; forvar codeI in code){ var true_code = code[codeI]; var result = UglifyJS.minifytrue_code, options); fs.writeFile'./dist/'+codeI, result.code, functionerr) { }); }
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').mapfile) => { console.logfile); var content = fs.readFileconFig.enterFile+file,'utf-8', function err,data) { code = {}; code[file] = data; Uglifycode) }); }); function deleteDist){ fs.readdirSyncconFig.outFile).mapfile) => { fs.unlinkconFig.outFile+`/${file}`,err) => { if err) { console.logerr); } else { console.log'delete ok'); } }); }); } function Uglifycode) { var options = { mangle: { toplevel: true, }, nameCache: {} }; forvar codeI in code){ var true_code = code[codeI]; var result = UglifyJS.minifytrue_code, options); fs.writeFileconFig.outFile+'/'+codeI, result.code, functionerr) { }); } }