如何发布自己的npm包


前言

我们经常使用的、封装的函数、组件可以发布到npm服务器上面去,

这样我们就不用在不同的项目写重复的代码了,

直接 npm i 安装引入

步骤

1. 新建一个文件夹

2. 在文件夹执行 npm init 命令
   
   这样就会生成package.json文件,进行相关的配置, 例如下面这样。
   
   可以设置打包编译的命令(我们会用到ts文件,因此使用 npx tsc -p 命令进行打包)。
   
   可以设置打包后文件、类型文件的目录。
{
  "name": "react-custom-hook-karlfranz",
  "version": "1.0.5",
  "description": "",
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "scripts": {
    "test": "jest",
    "build": "npx tsc -p .",
    "prepublishOnly": "npm run build"
  },
  "keywords": [
    "react",
    "hook"
  ],
  "author": "karlfranz",
  "license": "ISC",
  "dependencies": {
    "@types/node": "^20.11.22",
    "lodash": "^4.17.21",
    "react": "^18.2.0"
  },
  "devDependencies": {
    "@types/lodash": "^4.14.202",
    "@types/react": "^18.2.60"
  }
}
3. 创建src、dist文件夹

4. 在src文件夹下创建依赖的主体并暴露

5. 配置tsconfig.json
{
  "compilerOptions": {
    "target": "es5" /* 指定 ECMAScript 目标版本: 'ES3' (默认), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', 'ESNEXT'。 */,
    "module": "commonjs" /* 指定模块代码生成: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNEXT'。 */,
    "strict": true /* 启用所有严格的类型检查选项。 */,
    "forceConsistentCasingInFileNames": true /* 确保对大小写敏感的文件名解析。 */,
    "isolatedModules": true /* 将每个文件作为单独的模块进行编译(与 `ts.transpileModule` 类似)。 */,
    "lib": ["es6", "DOM", "ESNext"] /* 指定要包含在编译中的库文件列表。 */,
    "declaration": true,
    "sourceMap": true,
    "outDir": "./dist" /* 指定输出目录。 */,
    "rootDir": "./src",
    "esModuleInterop": true
  },
  "include": ["src"] /* 指定要包含在编译中的文件或目录。 */,
  "exclude": ["node_modules"] /* 指定要排除在编译之外的文件或目录。 */
}
6. 安装相关依赖

   我们定义的是一些react 自定义hook,因此需要安装react,
   
   若使用到其他依赖也需要安装。
   
7. 执行 npm login (需要npm 账号)

8. 执行 npm publish --access public (发布公共包,发布私有包不加后缀)

最后发布成功就能在npm看到我们刚刚发布的包了

https://www.npmjs.com/package/react-custom-hook-karlfranz

文章作者: KarlFranz
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 reprint policy. If reproduced, please indicate source KarlFranz !
评论
  目录