具有多个入口点的 TypeScript 包

Rad*_*ski 15 commonjs node-modules typescript es6-modules

公开节点包模块的标准方法是将它们列在index.ts中,如下所示:

export * from './module1';
export * from './module2';
Run Code Online (Sandbox Code Playgroud)

但是,这会立即加载两个模块的内容。我想要一个未在 index.ts 文件中导出的模块,因为它需要安装一些可选的依赖项。

我遵循了本指南:https://blog.mozilla.org/data/2021/04/07/this-week-in-glean-publishing-glean-js/

我的package.json:

  "exports": {
    ".": {
      "import": "./dist/es/index.js",
      "require": "./dist/cjs/index.js"
    },
    "./module2": {
      "import": "./dist/es/module2.js",
      "require": "./dist/cjs/module2.js"
    }
  },
  "typesVersions": {
    "*": {
      ".": [
        "./dist/types/index.d.ts"
      ],
      "./module2": [
        "./dist/types/module2.d.ts"
      ]
    }
  },
// fallback for older Node versions:
  "module": "dist/es/index.js",
  "main": "dist/cjs/index.js",
  "types": "dist/types/index.d.ts",
Run Code Online (Sandbox Code Playgroud)

在我构建项目后(使用tsc,分别用于 CJS 和 ESM),输出目录结构如下所示:

- dist
  - cjs
    - index.js
    - module2.js
  - es
    - index.js
    - module2.js
  - types
    - index.d.ts
    - module2.d.ts
Run Code Online (Sandbox Code Playgroud)

但是,当我发布此包并将其安装在客户端项目中时,module2 不起作用。

- dist
  - cjs
    - index.js
    - module2.js
  - es
    - index.js
    - module2.js
  - types
    - index.d.ts
    - module2.d.ts
Run Code Online (Sandbox Code Playgroud)

我运行它ts-node并收到错误:

src/index.ts:2:26 - error TS2307: Cannot find module 'ts-exports-test/module2' or its corresponding type declarations.
Run Code Online (Sandbox Code Playgroud)

注意:对于使用 TS 4.5 的客户端,可以在“exports”部分声明类型路径,从而无需“typesVersions”破解。但这是为了未来。

die*_*edu 23

如果您在 typesVersions 中定义路径,如下所示:

  "typesVersions": {
    "*": {
      "*": [
        "dist/types/index.d.ts"
      ],
      "module2": [
        "dist/types/module2.d.ts"
      ]
    }
  }
Run Code Online (Sandbox Code Playgroud)

不确定它遵循什么约定,但看起来像.或 的路径./无效。

您可以检查存储库https://github.com/diedu89/ts-export-import-test


Tha*_*you 11

2022 年,TypeScript 4.9 及更高版本

\n

exports优先于typesVersions

\n

以前,当通过under解析时,TypeScript 错误地将typesVersions字段优先于字段。如果此更改影响您的库,您可能需要在\xe2\x80\x99s字段中添加版本选择器。执行此操作的正确方法是现在使用 field -exportspackage.json--moduleResolution node16types@package.jsonexportsexports

\n
{\n      "type": "module",\n      "exports": {\n          ".": {\n              "import": "./dist/es/index.js",\n              "require": "./dist/cjs/index.js",\n              "types": "./dist/types/index.d.ts"  \xe2\x9c\x85\n          },\n          "module2" {\n              "import": "./dist/es/module2.js",\n              "require": "./dist/cjs/index.js",\n              "types": "./dist/types/module2.ts"  \xe2\x9c\x85\n          }\n      }\n  }\n
Run Code Online (Sandbox Code Playgroud)\n