npm 发布工具包

16 阅读1分钟

一、注册npm账号

二、建立gitee仓库

三、设置npm镜像仓库地址

npm config set registry https://registry.npmjs.org/

四、创建本地仓库

  • 创建项目mkdir utils image.png

  • 创建lib文件夹, 存放源代码比如index.ts image.png

  • 进入 utils项目,初始化项目 npm init image.png

  • 修改package.json中的入口文件 image.png

  • 安装typescript,执行命令npm install typescript --save-dev

  • 初始化tsconfig.json执行命令npx tsc --init image.png

  • 生成tsconfig.json文件后, 修改内容如下

 {
  "compilerOptions": {
    "target": "ESNext", // 指定 ECMAScript 目标版本: 'ES3' (default), 'ES5', 'ES6'/'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'
    "module": "ES6", // 指定生成代码的模块系统
    "outDir": "./dist",   // 指定输出目录
    "rootDir": "./lib",
    "strict": true,       // 启用所有严格类型检查选项
    "esModuleInterop": true, // 允许导入非 ES 模块
    "declaration": true, // 生成相对应的.d.ts文件
    "moduleResolution": "node",
    "forceConsistentCasingInFileNames": true,
    "skipLibCheck": true
  },
  "include": [
    "lib/*"
  ]
}

  • 配置package.json包基本信息
"type": "module",
  • 配置构建输出配置
  "main": "dist/index.js",
  "types": "./dist/index.d.ts",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "import": "./dist/index.js"
    }
  },
  • package.json文件中新增指令build,如下
"scripts": {
        ...
        "build": "tsc",          // 编译 TypeScript
        "prepublishOnly": "npm run build" // 发布前自动构建
      }
  • 创建.gitignore文件,内容如下
 node_modules

登录发布npm

  • 本地登录npm,执行命令:npm login image.png 点击链接登录 image.png 当出现Logged in on https://registry.npmjs.org/.表示登录成功

发布npm

  • npm私仓是收费的, 需要在package.json设置公开如下
  // 发布到 npm 的配置
  "publishConfig": {
    "access": "public",      // 公开包
    "registry": "https://registry.npmjs.org/" // 官方 registry
  },

  • 包含的文件列表(发布时会包含这些文件)
 "files": ["dist/", ".gitignore", "tsconfig.json", "package.json", "tsconfig.json"],
  • 发布npm publish image.png

至此发布成功