npm包发布流程实例
- 编写基础的模块代码
- 注册npm帐号(有的话直接进入下一步)
- 配置webpack
- 配置package.json
- 优化(ReadMe+单元测试)
- 发布
1. 编写一个简单的Math库
- math.js
// math.js
const square = x => x ** 2;
const cube = x => x ** 3;
export const MyMath = {
square,
cube
};
- date.js
// date.js
const padDateTime = x => {
try {
return +x < 9 ? x.toString().padStart(2, 0) : x.toString();
} catch (error) {
console.log(error);
}
};
export const MyDate = { padDateTime };
- index.js
// index.js入口文件
import { MyMath } from './math';
import { MyDate } from './date';
export { MyMath, MyDate };
2. npm注册
直接去npm官网进行注册即可
3. webpack配置
- filename: webpack打包后得到的包名
- library: 暴露导出库的全局变量名
- libraryTarget: 导出方式
- var: 允许通过script标签导入
- this: 通过this对象
- window: 通过注册到全局变量中
- umd: 允许以AMD或CMD, 一般导出包都是以这种形式
- externals如果有一些导入的包不想打包在自己的库中,依赖外部包可以进行配置
配置完之后进行webpack进行打包
webpack --config webpack.config.js
4. 配置发布package.json
5. 优化
略
6. 发布流程
# 完成git上的代码提交流程后执行下面的步骤
# npm登录 输入登录信息
npm login
# 如果用的是淘宝源先切回npm源
npm config set registry http://registry.npmjs.org
# 接入npm
npm adduser
# 发布
npm publish
- npm adduser
- npm publish
7. 测试包导入
yarn add bad-egg-tools
发现可以正常导入, 并且使用,大功告成啦~
参考
代码已经上传: github代码
从0开始发布包
webpack配置文档