携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第20天,点击查看活动详情
js代码压缩包
minify
使用
安装:
npm i minify -g
使用:
minify hello.js > hello.min.js
一些配置:
{
"html": {
"removeAttributeQuotes": false
},
"css": {
"compatibility": "*"
},
"js": {
"ecma": 5
},
"img": {
"maxSize": 4096
}
}
html-minifier压缩配置:
{
"removeComments": true,
"removeCommentsFromCDATA": true,
"removeCDATASectionsFromCDATA": true,
"collapseWhitespace": true,
"collapseBooleanAttributes": true,
"removeAttributeQuotes": true,
"removeRedundantAttributes": true,
"useShortDoctype": true,
"removeEmptyAttributes": true,
"removeEmptyElements": false,
"removeOptionalTags": true,
"removeScriptTypeAttributes": true,
"removeStyleLinkTypeAttributes": true,
"minifyJS": true,
"minifyCSS": true
}
UglifyJS/UglifyES
安装:
npm install uglify-js -g
命令行压缩使用:
uglifyjs [input files] [options]
文件压缩示例:
uglifyjs js/file1.js js/file2.js \
-o foo.min.js -c -m \
--source-map "root='http://foo.com/src',url='foo.min.js.map'"
多文件压缩:
var code = {
"file1.js": "function add(first, second) { return first + second; }",
"file2.js": "console.log(add(1 + 2, 3 + 4));"
};
var result = UglifyJS.minify(code);
一些压缩配置项:
{
parse: {
// parse options
},
compress: {
// compress options
},
mangle: {
// mangle options
properties: {
// mangle property options
}
},
output: {
// output options
},
sourceMap: {
// source map options
},
nameCache: null, // or specify a name cache object
toplevel: false,
warnings: false,
}
压缩代码处理
通过配合fs文件处理器,压缩代码。生成压缩后的代码文件。 部分关键代码如下:
const fs = require('fs-extra');
const path = require('path');
const glob = require('glob');
const UglifyJS = require('uglify-es'); // 引入uglify-es压缩处理
const HTMLMinifier = require('html-minifier');
function minify(srcfolder, outfolder) {
console.log("srcfolder", srcfolder)
console.log("outfolder", outfolder)
const srcPath = path.resolve(process.cwd(), srcfolder);
const buildPath = path.resolve(process.cwd(), outfolder);
// 将源码目录复制到新目录中
fs.copySync(srcPath, buildPath, {
overwrite: true,
errorOnExist: false,
});
// 压缩SDK目录文件
// 压缩JS文件
const jsFiles = glob.sync('**/*.js', {
cwd: buildPath,
});
jsFiles.forEach((file) => {
const srcFile = path.join(buildPath, file);
console.log('minify>', srcFile);
fs.outputFileSync(
srcFile,
UglifyJS.minify(fs.readFileSync(srcFile, 'utf8'), {
compress: {
dead_code: true,
drop_debugger: true,
booleans: true,
unused: true,
join_vars: true
},
mangle: true,
}).code,
'utf8',
);
});
// 压缩模板文件
const tplFiles = glob.sync('**/**/*.{js}', {
cwd: buildPath,
});
tplFiles.forEach((file) => {
const srcFile = path.join(buildPath, file);
fs.outputFileSync(
srcFile,
HTMLMinifier.minify(fs.readFileSync(srcFile, 'utf8'), {
removeComments: true,
collapseWhitespace: true,
keepClosingSlash: true,
}),
'utf8',
);
});
}
module.exports = {
minify
}