大家好, 我是 老麦, 一个运维老兵, 现在专注于 Golang,DevOps,云原生基础设施建设。
建议点击 查看原文 查看最新内容。
原文链接: https://typonotes.com/posts/2025/03/01/intro-of-npm-package-publish/
npm 发包必须要注册一个 npm registry 的账号。 包名全局唯一
$ npm login
$ npm publsh
在 package.json
中管理 包的定义
{
"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[1]
基于 typescript
npm init
并安装 typescript 依赖$ npm init
$ npm install -D typescript
配置 tsconfig.json
{
"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
}
}
moduleResolution
: https://www.typescriptlang.org/tsconfig/#moduleResolution当 tsconfig.json
中的 module 为非 commonjs
的时候, Connot require() ES Module ... in a cycle
错误。
// tsconfig.json
"module": "ESNext", // 非 commonjs
不知道是否是由于 ioredis
的模式引起的。 参考 ioredis 的 tsconfig.json[2] 之后, 修改为 commonjs
后, 问题解决。
import IORedisClient from 'ioredis-client'
const endpoint = 'redis://:dummypass@localhost:6379/1';
const rc = new IORedisClient(endpoint)
当没有直接导出 ioredis.ts
的时候, 没有为 commonjs
配置 exports
的时候, 遇到当前问题
解决方法: 创建一个 index.ts
管理 统一导出 的问题。
// index.ts
// for commonjs
exports = module.exports = require("./lib/ioredis").default;
// for module
export { default } from "./lib/ioredis";