从 NPM 包中导出多个模块

Export multiple modules from NPM package

我有一个使用 Node 和 Typescript 的相当大的项目 A。在项目 A 中,我有很多不同的模块,我想在另一个项目 B 中重用它们。

因此我用这个 tsconfig.json 构建了项目 A:

{
    "compilerOptions": {
        "target": "es2017",
        "module": "commonjs",
        "declaration": true,
        "outDir": "./dist",
        "sourceMap": true,
        "strict": true,
        "noImplicitAny": true,
        "strictNullChecks": true,
        "typeRoots": ["./node_modules/@types", "./modules/@types"]
    },
    "exclude": ["node_modules"]
}

因此所有文件都以这种方式内置到 /dist 文件夹中:

要在另一个项目中使用这些 moduleA 和 moduleB,我将以下内容添加到项目 A 中的 package.json:

    "name": "projectA",
    "version": "1.0.0",
    "description": "...",
    "main": "dist/moduleA.js",
    "typings": "dist/moduleA.d.ts",

我使用 yarn workspaces 来访问项目 A 作为项目 B 中的一个包。但是问题是,在我的新项目 B 中使用 import {ModuleA} from 'projectA' 时,我只能访问模块 A?那么如何从 ProjectA 访问更多模块?

将所有出口合并为一个 index.ts 是否适合您?

package.json(项目 A):

{
  "main": "dist/index.js",
  "typings": "dist/index.d.ts",
  ...
}

index.ts(项目 A):

// Adjust the relative import paths 
// and identifiers to your structure
export { ModuleA } from "./moduleA";
export { ModuleB } from "./moduleB";

项目B中的某个模块:

import {ModuleA, ModuleB} from 'projectA'

我相信您正在寻找的是: https://nodejs.org/api/packages.html#packages_package_entry_points

不清楚 TypeScript 目前是否支持: https://github.com/microsoft/TypeScript/issues/33079

看起来你确实可以解决这个问题,尽管在你的 package.json:

中使用类似的东西
{
    ...

    "main": "./dist/index.js",
    "types": "./dist/index.d.ts",
    "typesVersions": {
        "*": {
          "dist/index.d.ts": [ "dist/index.d.ts" ],
          "*": [ "dist/*" ]
        }
      },
    "exports": {
        ".": "./dist/index.js",
        "./": "./dist/"
    },

    ...
}