【问题标题】:Export multiple modules from NPM package从 NPM 包中导出多个模块
【发布时间】:2019-12-22 03:34:30
【问题描述】:

我有一个使用 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.js
    • moduleA.map
    • moduleA.d.ts
    • moduleB.js
    • moduleB.map
    • moduleB.d.ts
    • ....

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

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

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

【问题讨论】:

    标签: node.js typescript npm yarnpkg yarn-workspaces


    【解决方案1】:

    将所有导出合并到一个 index.ts 中对您有用吗?

    package.json (projectA):

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

    index.ts (projectA):

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

    项目B中的一些模块:

    import {ModuleA, ModuleB} from 'projectA'
    

    【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2020-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多