webpack4之方法库项目打包


基础配置

新建项目
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# npm init -y

// package.json
{
"name": "ethan-methods", // 唯一的名字
"version": "1.0.0",
"description": "",
"main": "./dist/library.js", // 我们这个库,最终给别人使用的是dist目录下的library文件
"scripts": {
"build": "webpack --config ./build/webpack.prod.js",
"myPublish": "git push && npm publish --registry=https://registry.npmjs.org/" // 发布指定npm地址
},
"keywords": [],
"author": "",
"license": "MIT" // 设置为开源库
}

// webpack.config.js
const path = require('path')
const {CleanWebpackPlugin} = require('clean-webpack-plugin');

module.exports = {
mode: 'production',
entry: './src/index.js',
externals: ["lodash"], // 将库里的第三方依赖包不进行打包,不然使用的时候可能用了相同的依赖包,这样就有重复代码了
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'library.js',
library: 'fn', // fn为window的全局变量:通过<script>引入到全局变量
libraryTarget: 'umd' // umd: 通用的引入:import引入,commonJs引入,AMD引入
},
plugins: [
new CleanWebpackPlugin()
]
}

npm上传自己的包

npm账号密码
1
2
userName: ethan6
password: 常用新密码10位
命令行
1
2
3
4
# nrm use npm
# npm login
# npm publish
# npm unpublish 依赖包名称 --force // 删除包