打包方式和打包项目时类似
思路:
(1)输出代码的压缩和未压缩版本文件
将src下的源代码进行打包输出,设置entry分别对应压缩和未压缩版本,设置mode:'none'可使得打包都不压缩
(2)控制压缩文件对应的压缩,未压缩文件不压缩
通过optimization中的new TerserPlugin压缩插件匹配.min.js压缩版本文件,进行压缩打包输出
(3)引入库时,根据当前运行环境判断引入压缩文件还是非压缩文件
在项目的index.js入口文件中,根据process.env.NODE_ENV=='production'来判断是引入压缩文件还是非压缩文件
然后使用module.exports=require('文件路径')将其导出
其中:
不使用export等是因为node环境使用commonjs语法
该文件仅作判断后导出处理,当下载包后,import xx from XX即可使用
(1)下载压缩插件
cnpm install terser-webpack-plugin@4 -D
webpack5不需要下载
(2)配置
module.exports = {
entry: { 设置源代码入口
"add": './src/index.js', 非压缩版
"add.min":'./src/index.js' 压缩版
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js', 根据入口chunk名称导出
library: '暴露的库名称',
libraryTarget: 'umd', 将你的library暴露为所有的模块定义下都可运行的方式,如amd、cmd等
libraryExport:'default' 库导出时添加了.default导出,即下载该库后,import x from XX,直接导入即可,而不需要添加XX.default
},
mode: 'none', 不压缩代码
optimization: {
minimize: true, 使用minimizer中的压缩插件
minimizer: [
new TerserPlugin({
test:/\.min\.js$/ 匹配压缩的chunk,即只压缩min.js文件
})
]
}
}
(3)项目入口文件index.js根据环境导出对应打包后的文件
if (process.env.NODE_ENV == 'production') {
module.exports=require('./dist/xx.min.js')
} else {
module.exports=require('./dist/xx.js')
}
(4)打包发布
"name":"库名称",
"description":"库描述",
"script":{
"build":"webpack"
"prepublish":"webpack"
}
添加prepublish钩子,表示执行npm publish的时候会执行该命令
先npm login登录npm账号
(4)使用
npm下载该包名称即package.json中name设置的名称,import导入即可使用
代码示例:
库的源代码放置在src下面,库的入口文件仅做导入判断处理,故只需压缩src下的文件
webpack.config.js:
const path = require('path');
const TerserPlugin = require("terser-webpack-plugin");
const setOptions = ()=>{
const entry = {};
const htmlWebpackPlugin = [];
const entryFiles = glob.sync(path.resolve(__dirname, './src/*/index.js'))
const fileReg = /src\/(.*)\/index\.js/;
entryFiles.forEach((filePath, index) => {
const fileName = filePath.match(fileReg);
entry[fileName[1]] = filePath;
htmlWebpackPlugin.push(
new HtmlWebpackPlugin({
template: `./src/${fileName[1]}/index.html`,
filename:fileName[1]+'.html',
chunks:[fileName[1]]
})
)
})
return {
entry,
htmlWebpackPlugin
}
}
module.exports = {
entry: {
"add": './src/index.js', //非压缩版
"add.min":'./src/index.js' //压缩版
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js',
library: 'addNum',
libraryTarget: 'umd',
libraryExport:'default'
},
mode: 'none',
optimization: {
minimize: true, //使用minimizer中的压缩插件
minimizer: [
new TerserPlugin({
test:/\.min\.js$/ //匹配压缩的chunk
})
]
}
}
项目入口文件index.js:
if (process.env.NODE_ENV == 'production') {
module.exports=require('./dist/add.min.js')
} else {
module.exports=require('./dist/add.js')
}