编译压缩单个文件
# babel 6 方式编译压缩 js 文件
- 新建工程文件夹,进入该文件夹执行初始化
npm init
- 安装依赖
npm i --save-dev babel-cli babel-preset-env terser
- 在工程文件夹根目录,新建
.babelrc文件,并新增内容
{
"presets": [
["env", {
"modules": false, // 保留 ES6 模块语法
"targets": {
"esmodules": true // 或指定浏览器版本,如 "chrome": 58
}
}]
]
}
- 在工程文件夹根目录,新建
source文件夹用于存放源码文件,新建dist文件夹用于存放编译压缩后的文件 - 执行编译压缩
- 方式一,直接使用命令行
npx babel source/index.js | npx terser -o dist/index.min.js --compress --mangle --module- 方式二,在
package.json文件新增一条script命令,后续执行npm run build即可
"scripts": { "build": "npx babel source/index.js | npx terser -o dist/index.min.js --compress --mangle --module" }
# 编译压缩 js 文件(兼容性好)
- 新建一个工程文件夹,进入该文件夹,切换 node 高版本并执行 npm 初始化
nvm use 20
npm init
- 安装依赖
npm i --save-dev @babel/cli @babel/core @babel/preset-env terser webpack webpack-cli
npm i babel-loader bable-loader terser-webpack-plugin
- 在工程文件夹根目录,新建
.babelrc文件,新增内容
// .babelrc
{
"presets": [
[
"@babel/preset-env",
{
"targets": {
"ie": "9"
},
"modules": false
}
]
]
}
- 在工程文件夹根目录,新建
terser.config.js文件,新增内容
// terser.config.js
module.exports = {
compress: {
comparisons: false,
conditionals: false,
dead_code: true,
drop_console: false,
evaluate: false,
hoist_funs: false,
hoist_vars: false,
if_return: false,
join_vars: false,
loops: false,
side_effects: true,
unused: true
},
mangle: {
keep_fnames: false,
reserved: []
},
output: {
comments: false,
ie8: true
},
ecma: 5,
ie8: true
}
- 在工程文件夹根目录,新建
webpack.config.js文件,新增内容
// webpack.config.js
const path = require('path')
module.exports = {
entry: './source/index.js',
output: {
filename: 'index.min.js',
path: path.resolve(__dirname, 'dist'),
libraryTarget: 'umd',
globalObject: 'this'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
[
'@babel/preset-env',
{
targets: {
ie: '9'
},
modules: false
}
]
]
}
}
}
]
},
mode: 'production',
optimization: {
minimize: true,
minimizer: [
compiler => {
const TerserPlugin = require('terser-webpack-plugin')
new TerserPlugin({
terserOptions: {
ie8: true,
ecma: 5,
compress: {
comparisons: false,
conditionals: false,
ie8: true
},
mangle: {
ie8: true
},
output: {
ie8: true,
comments: false
}
}
}).apply(compiler)
}
]
}
}
- 在
package.json文件新增script命令
// package.json
"scripts": {
"build": "webpack --mode=production"
}
在工程文件夹根目录,新建
source文件夹用于存放源码和dist文件夹用于存放编译压缩后的代码执行编译压缩
npm run build