webpack除了打包应用,也可以用来打包js库
- 需要打包压缩版和非压缩版本
- 支持 AMD/CJS/ESM 模块引入
如何将库暴露出去?
- library:指定库的全局变量
- libraryTarget:支持库引入的方式
1、新建项目,并安装webpack和wbpack-cli
npm init -y
npm i webpack webpack-cli -D
2、新建目录 src/index.js, 此处使用大整数求和算法作为案例
export default function add(a, b) {
let i = a.length - 1
let j = b.length - 1
let carry = 0
let ret = ''
while (i >= 0 || j >= 0) {
let x = 0
let y = 0
let sum
if (i >= 0) {
x = a[i] - '0'
i --
}
if (j >= 0) {
y = b[j] - '0'
j --
}
sum = x + y + carry
if (sum >= 10) {
carry = 1
sum -= 10
} else {
carry = 0
}
ret = sum + ret
}
if (carry) {
ret = carry + ret
}
return ret
}
// add('1', '999')
// add('999', '1')
// add('99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999', '1')
3、安装terser-webpack-plugin压缩插件
npm i terser-webpack-plugin -D
4、新建webpack.config.js文件
const TerserPlugin = require('terser-webpack-plugin') // 引入压缩插件
module.exports = {
entry: {
'large-number': './src/index.js',
'large-number.min': './src/index.js'
},
output: {
filename: '[name].js',
library: 'largeNumber',
libraryTarget: 'umd',
libraryExport: 'default'
},
mode: 'none', // 设置mode为none避免默认压缩
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({ // 使用压缩插件
include: /\.min\.js$/
})
]
}
}
5、配置package.json文件
{
"name": "large-number",
"version": "1.0.0",
"description": "大整数加法打包", // 包或者库的描述
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack",
"prepublish": "webpack" // 钩子
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"terser-webpack-plugin": "^1.3.0",
"webpack": "^4.34.0",
"webpack-cli": "^3.3.5"
}
}
6、设置入口文件,由于package.json的main字段为index.js,故添加index.js文件
if (process.env.NODE_ENV === 'production') { // 通过环境变量来决定入口文件
module.exports = require('./dist/large-number.min.js')
} else {
module.exports = require('./dist/large-number.js')
}
7、发布(需要npm账号,且登入)
npm publish
8、README文档看情况补充,此时发布成功,可通过npm i large-number -s在其他项目中引入该库