You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TypeScript库项目中生成子模块?br-store路径导入配置

实现br-store库的深层路径导入支持

要让你的br-store库支持import { getAlarms } from "br-store/alarm/actions"这类深层路径导入,你需要调整编译配置和package.json的导出映射,以下是具体步骤:

1. 确保编译后保留源码目录结构

你的tsconfig.json已经配置了rootDir: "./src"和outDir: "./bin",这一步是正确的——TypeScript会按照src的目录结构,把编译后的.js和.d.ts文件输出到bin目录下。运行tsc之后,你应该能看到bin目录里有和src对应的结构:

./bin/store/
├── alarm
│   ├── alarm-actions.js
│   ├── alarm-actions.d.ts
│   ├── alarm-constants.js
│   ├── alarm-constants.d.ts
│   ├── alarm-reducer.js
│   ├── alarm-reducer.d.ts
│   └── index.js
│   └── index.d.ts
|__ index.js
|__ index.d.ts

如果结构不对,检查tsconfig的include是否覆盖了所有src下的文件,确保没有遗漏。

2. 配置package.json的exports字段

exports字段是Node.js用来定义包的入口映射的,它能让你指定每个导入路径对应的实际文件。在你的package.json中添加以下配置:

"exports": {
  ".": "./bin/store/index.js",
  "./alarm/actions": "./bin/store/alarm/alarm-actions.js",
  "./alarm/constants": "./bin/store/alarm/alarm-constants.js",
  "./alarm/reducer": "./bin/store/alarm/alarm-reducer.js",
  "./alarm": "./bin/store/alarm/index.js"
}

这个配置的意思是:

  • 当用户导入br-store时,指向主入口./bin/store/index.js
  • 当用户导入br-store/alarm/actions时,指向编译后的actions文件./bin/store/alarm/alarm-actions.js
  • 以此类推,覆盖你需要支持的所有深层路径

3. 配置TypeScript类型映射(typesVersions)

为了让TypeScript能正确识别深层路径的类型定义,需要在package.json中添加typesVersions字段:

"typesVersions": {
  "*": {
    "alarm/actions": ["./bin/store/alarm/alarm-actions.d.ts"],
    "alarm/constants": ["./bin/store/alarm/alarm-constants.d.ts"],
    "alarm/reducer": ["./bin/store/alarm/alarm-reducer.d.ts"],
    "alarm": ["./bin/store/alarm/index.d.ts"]
  }
}

这个配置告诉TypeScript,当匹配到br-store/alarm/actions这样的路径时,去对应的.d.ts文件找类型定义。

4. 确保发布时包含编译后的文件

在package.json的files字段中添加bin目录,确保发布到npm时所有编译后的文件都被包含:

"files": [
  "bin/**/*"
]

测试验证

完成以上配置后,重新运行tsc编译你的库,然后在测试项目中尝试导入:

import { getAlarms } from "br-store/alarm/actions";

此时应该能正确导入函数,并且TypeScript能识别对应的类型。

补充说明

  • 如果你需要支持更多深层路径,只需要在exports和typesVersions中添加对应的映射即可
  • 这种方式符合现代npm包的导出规范,同时兼容Node.js和TypeScript环境

内容的提问来源于stack exchange,提问作者raven

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:21:10