从 NPM 包导出多个模块

Jol*_*lle 10 node.js npm typescript yarnpkg yarn-workspaces

我有一个相当大的项目 A 使用 Node 和 Typescript。在项目 AI 中有很多不同的模块,我想在另一个项目 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"]
}
Run Code Online (Sandbox Code Playgroud)

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

  • 距离
    • moduleA.js
    • 模块A.map
    • 模块广告
    • moduleB.js
    • moduleB.map
    • 模块B.d.ts
    • ....

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

    "name": "projectA",
    "version": "1.0.0",
    "description": "...",
    "main": "dist/moduleA.js",
    "typings": "dist/moduleA.d.ts",
Run Code Online (Sandbox Code Playgroud)

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

for*_*d04 9

简单地将所有出口合并为一个index.ts对您有用吗?

package.json(项目A):

{
  "main": "dist/index.js",
  "typings": "dist/index.d.ts",
  ...
}
Run Code Online (Sandbox Code Playgroud)

索引.ts(项目A):

// Adjust the relative import paths 
// and identifiers to your structure
export { ModuleA } from "./moduleA";
export { ModuleB } from "./moduleB";
Run Code Online (Sandbox Code Playgroud)

项目B中的一些模块:

import {ModuleA, ModuleB} from 'projectA'
Run Code Online (Sandbox Code Playgroud)

  • 这并不能回答问题。如果您不想包含模块或想要处理更大的文件怎么办? (7认同)

Mic*_*ign 9

我相信您正在寻找的是: 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/"
    },

    ...
}
Run Code Online (Sandbox Code Playgroud)