从 NPM 包中导出多个模块

2023-12-22

我有一个相当大的项目 A 使用 Node 和 Typescript。在项目 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 文件夹中:

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

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

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

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


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

不清楚 TypeScript 目前是否支持:https://github.com/microsoft/TypeScript/issues/33079 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/"
    },

    ...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从 NPM 包中导出多个模块 的相关文章

随机推荐