Typescript NPM 制包/发包问题解析

建议点击 查看原文 查看最新内容。

原文链接: https://typonotes.com/posts/2025/03/01/intro-of-npm-package-publish/

NPM 发包

npm 发包必须要注册一个 npm registry 的账号。 包名全局唯一

  1. 访问 https://www.npmjs.com/ 并注册一个账号

  2. 本地登录

1
$ npm login
  1. 发布
1
$ npm publsh

包的定义

package.json 中管理 包的定义

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
{
  "name": "ioredis-client", // 包名
  "version": "1.0.7", // 版本
  "main": "dist/index.js", // 默认入口文件。 指定后, 可以直接使用包名。
  "types": "dist/index.d.ts", // ts 默认类型文件。
  "files": [  // files 指定上传哪些文件。 
    "dist"
  ],
  "type": "commonjs", // 包类型, commonjs 或者 module
  // ...
}

其他类似 author, license, keywords, repository 等关键字, 可以参考开源公共库 ioredis package.json

NPM 制包: ioredis 单例/集群 客户端

基于 typescript

  1. 使用 npm init 并安装 typescript 依赖
1
2
$ npm init
$ npm install -D typescript

配置 tsconfig.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
{
    "compilerOptions": {
        "rootDir": "./src",  // 源文件目录
        "outDir": "./dist",  // 编译后的目标文件目录

        "target": "ES2019",  // 编译成 js 的版本。 
        "module": "commonjs", // 包管理模式。

        "strict": true,   // ts 严格模式
        "declaration": true,  // 生成 ts 声明文件  xxx.d.ts
        "moduleResolution": "node",  // 包解析器

        "lib": [  // library: 基于 ioredis 包源文件。 
            "es2019",
            "es2020.bigint",
            "es2020.string",
            "es2020.symbol.wellknown"
        ],

        "moduleDetection": "force", 
        "skipLibCheck": true,
        "forceConsistentCasingInFileNames": true,
        "noPropertyAccessFromIndexSignature": false
    }
}

TroubleShoot

1.

tsconfig.json 中的 module 为非 commonjs 的时候, Connot require() ES Module ... in a cycle 错误。

1
2
// tsconfig.json
    "module": "ESNext", // 非 commonjs

alt text

不知道是否是由于 ioredis 的模式引起的。 参考 ioredis 的 tsconfig.json 之后, 修改为 commonjs 后, 问题解决。

2. IORedisClient is not a constructor

1
2
3
4
import IORedisClient from 'ioredis-client'

const endpoint = 'redis://:dummypass@localhost:6379/1';
const rc = new IORedisClient(endpoint)

当没有直接导出 ioredis.ts 的时候, 没有为 commonjs 配置 exports 的时候, 遇到当前问题

解决方法: 创建一个 index.ts 管理 统一导出 的问题。

1
2
3
4
5
6
7
// index.ts

// for commonjs
exports = module.exports = require("./lib/ioredis").default;

// for module
export { default } from "./lib/ioredis";

2. cylelopp