这里简单记录一下 npm
包的创建和发布流程。
创建
在项目中通过 npm init
可创建 package.json 文件,之后填写内容大致如下:
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 36 37 38 39 40 41
| { "name": "@qiweipeng/use-axios", "version": "1.0.0", "description": "An axios hook.", "main": "./lib/index.js", "types": "./lib/index.d.ts", "files": [ "/lib" ], "scripts": { "build": "rm -rf ./lib && tsc", "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/qiweipeng/useAxios.git" }, "keywords": [ "axios", "zod" ], "author": "Weipeng Qi <qiweipeng@hotmail.com>", "license": "MIT", "bugs": { "url": "https://github.com/qiweipeng/useAxios/issues" }, "homepage": "https://github.com/qiweipeng/useAxios#readme", "dependencies": { "@anatine/zod-mock": "^3.12.0", "@faker-js/faker": "^8.0.0", "axios": "^1.3.0", "zod": "^3.21.0" }, "devDependencies": { "@types/react": "^18.0.0", "typescript": "^4.4.2" }, "peerDependencies": { "react": "^18.0.0" } }
|
同时,在项目根目录创建 index.ts
文件,该文件作为入口文件,暴露项目中需要公开的文件。如:
1 2 3 4 5
| export {default as axios} from './src/axios' export * from './src/useAxios' export * from './src/useValidatedAxios' export {default as useUpdateRef} from './src/utils/useUpdateRef'
|
下面解释一下 package.json
中的部分字段的设置:
name
:包名,其中 qiweipeng
是 npm 网站中的用户名,如此设置后,安装的命令就是如 yarn add @qiweipeng/use-axios
;
version
:版本号,这个每次发版更新即可;
main
和 types
:分别代表了编译之后 JavaScript
和 TypeScript
的入口文件,由于编译之后的目录是 ./lib
文件夹,而我们预先设置的入口文件是在根目录,所以设置的路径分别是 ./lib/index.js
和 ./lib/index.d.ts
;
files
:表示发布的代码的目录,这里需要设置为编译后的目录,即 /lib
;
scripts
-build
:编译命令,代码完成后需要执行该命令编译代码;
dependencies
:发布的包的依赖;
另外,需要注意在 tsconfig.json
文件中,加入如下两个字段:
1 2
| "outDir": "./lib", "rootDir": "./",
|
因为 ./lib
文件夹没必要提交到 Git
,所以最好在 .gitignore
中加入 lib
进行忽略。
发布
代码完成后执行 npm build
编译代码,之后使用 npm login
可以登录账号,登录完成后使用 npm publish --access public
即可发布。
另外,如果代码仓库是私有库,又或者我们发布的仓库不是 npm
官方的仓库而是自建库,那么可以在根目录创建 .npmrc
文件来进行设置:
1 2
| registry="http://xxx.xxx/" //xxx.xxx/:_authToken=abbe5034-c886-26b6-a324-2f3c701de522
|
其中第一行代表了包发布的地址,第二行的含义是给某个地址设置 _authToken
,即一次性密码,设置后即使本地没有登录,也可以读取该密码进行登录来发包。