使用子路径导出时无法使Typescript定义工作

sdnqo3pr  于 2023-05-19  发布在  TypeScript
关注(0)|答案(1)|浏览(111)

在我的项目(latest commit)中,我的package.json中有两个导出:

  1. "exports": {
  2. ".": "./dist/index.js",
  3. "./react-lazy": "./dist/react-lazy.js"
  4. },

在JS项目中使用它可以很好地工作,但是TS项目抱怨在我将一个模块分割成子路径导出后找不到类型。
然后我尝试了我在another answer中看到的“扩展”导出版本:

  1. "exports": {
  2. ".": {
  3. "import": "./dist/index.js",
  4. "types": "./types/index.d.ts"
  5. },
  6. "./react-lazy": {
  7. "import": "./dist/react-lazy.js",
  8. "types": "./types/react-lazy.d.ts"
  9. }
  10. },

不行
然后我尝试了另一种方法,使用typesVersion

  1. "typesVersions": {
  2. "*": {
  3. ".": "./types/index.d.ts",
  4. "./react-lazy": "./types/react-lazy.d.ts"
  5. }
  6. },

也不去。怎么回事?现在我有点搞不清楚这里的问题是什么。
在尝试这个方法时,我从测试项目中执行npm linknpm link @fatso83/retry-dynamic-import,然后运行tsc --lib es2015,dom --noEmit main.ts
我基本上只是测试这些行是否通过编译器:

  1. import { dynamicImportWithRetry } from "@fatso83/retry-dynamic-import";
  2. import reactLazy from "@fatso83/retry-dynamic-import/react-lazy";

目前,所有上述尝试都以

  1. $ tsc --lib es2015,dom --noEmit main.ts
  2. main.ts:3:40 - error TS2307: Cannot find module '@fatso83/retry-dynamic-import' or its corresponding type declarations.
  3. 3 import { dynamicImportWithRetry } from "@fatso83/retry-dynamic-import";
  4. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

如果我只是导出index.js,一切都很好,因为这是这样工作的:

  1. "exports": "./dist/index.js",
  2. "types": "./types/index.d.ts",

这将使第一条线通过,但不是第二条。

pnwntuvh

pnwntuvh1#

The answer that got everything working是TypeScript支持子路径导入,如果且仅当您将moduleResolution设置为nodeNextnode16时。
不幸的是,无论出于何种原因,这都将迫使您在动态导入时指定文件扩展名(如import('./foo.ts'))。
所以上面的TSC命令只是稍微调整了一下:

  1. $ npx tsc --esModuleInterop true --lib es2015,dom --noEmit --moduleResolution nodeNext main.ts

然后一切都在工作。

  • 不幸的是 *,我不确定其他消费者会认为这有多热...这意味着要么暴露一个可能以传递方式拉入React的包(如果不使用子路径导出),即使不使用它,要么强制消费者向其动态导入添加扩展。

相关问题