发布基于typescript的npm包

如何发布一个npm包

一个npm只需要包含带有nameversionpackage.json文件就可以了,实际上还需要做一些准备工作。

注册npm账号

在这注册
然后在命令行使用npm adduser或者npm login输入你的usernamepasswordemail

开始开发一个包

创建一个文件夹,添加预设的package.json

{
"name": "@furo_yang/tiny",
"version": "1.0.0"
}

发布一个空包

如果直接npm publish发布的包是私有的,这里先设为公开。

npm publish --access=public

更新代码以及版本

npm使用的版本控制是semver。这里给这个包添加一个index.js作为入口,再更新版本。

npm major

创建基于typescript的npm包模板

在上一步已经知道了如何发布一个基本的包了,但是我们发布包的时候不可能每次都重复这样的操作。基于以上,是时候创建一个npm包模板工程了。

# 创建文件夹
mkdir tiny
cd tiny
# 初始化git仓库
git init
touch .gitignore
echo "# npm packge template based on typescript" >> README.md
# 安装typescript
npm install typescript --save
npm init --y
# 创建tsconfig.json
./node_modules/.bin/tsc --init
```
#### 修改tsconfig.json
```JSON
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"declaration": true,
"strict": true,
"outDir": "./lib",
"esModuleInterop": true
},
"include": ["src"],
"exclude": ["node_modules", "**/__tests__/*"]
}

添加npm脚本

{
"scripts": {
"start": "tsc -w",
"build": "tsc"
}
}

编写代码

mkdir src
cd src
touch index.ts

# index.ts
export const Greeter = (name: string) => `Hello ${name}`;

添加忽略提交的文件以及文件夹

node_modules
/lib

添加单元测试

npm install jest ts-jest @types/jest --save
配置jestconfig.json文件

{
"transform": {
"^.+\\.(t|j)sx?$": "ts-jest"
},
"testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
"moduleFileExtensions": ["ts", "tsx", "js", "jsx", "json", "node"]
}

再配置package.json里的test命令"test": "jest --config jestconfig.json"

发布npm package

npm version major
npm publish --access=public
文章作者: Furo Yang
文章链接: http://furoteam.cn/2021/01/19/发布npm包/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 furoのBlog