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

如何将NPM包配置为支持模块化路径导入?

实现NPM包子模块导入的配置修改方案

要让你的NPM包支持my-package/products、my-package/sales这类子模块导入,需要调整项目结构、package.json和tsconfig.json,具体步骤如下:

1. 确认项目目录结构

确保src目录下的子模块按独立目录组织,每个目录包含自己的入口文件:

src/
├── index.ts       # 保留原有导出,兼容旧导入方式(可选)
├── products/
│   └── index.ts   # 导出myFunction1
└── sales/
    └── index.ts   # 导出myFunction2

示例src/products/index.ts内容:

export const myFunction1 = () => {
  // 函数逻辑
};

2. 修改package.json配置

添加exports字段,明确指定每个子模块的入口文件,同时配置TypeScript类型文件路径:

{
  "name": "my-package",
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "exports": {
    ".": {
      "require": "./dist/index.js",
      "import": "./dist/index.js",
      "types": "./dist/index.d.ts"
    },
    "./products": {
      "require": "./dist/products/index.js",
      "import": "./dist/products/index.js",
      "types": "./dist/products/index.d.ts"
    },
    "./sales": {
      "require": "./dist/sales/index.js",
      "import": "./dist/sales/index.js",
      "types": "./dist/sales/index.d.ts"
    }
  },
  "scripts": {
    "build": "rm -rf ./dist && tsc"
  },
  "devDependencies": {
    "typescript": "^5.2.2"
  }
}

注:exports是Node.js识别子模块的核心配置,types字段用于确保TypeScript能正确识别子模块的类型定义。

3. 调整tsconfig.json配置

确保TypeScript编译时覆盖所有子模块文件,并输出到dist对应目录:

{
  "compilerOptions": {
    "incremental": true,
    "target": "es2020",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "module": "commonjs",
    "baseUrl": "./src",
    "declaration": true,
    "outDir": "./dist",
    "removeComments": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "strictNullChecks": false,
    "skipLibCheck": true
  },
  "include": ["src/**/*"]
}

添加include: ["src/**/*"]确保src下所有子目录的文件都会被编译,避免子模块代码未输出到dist目录。

4. 验证效果

运行npm run build后,dist目录会生成对应结构:

dist/
├── index.js
├── index.d.ts
├── products/
│   ├── index.js
│   └── index.d.ts
└── sales/
    ├── index.js
    └── index.d.ts

此时在其他项目中,就可以通过以下方式导入子模块:

import { myFunction1 } from 'my-package/products';
import { myFunction2 } from 'my-package/sales';

同时原有import { myFunction1, myFunction2 } from 'my-package';的导入方式依然可用(如果保留了src/index.ts的导出)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 10:55:23