为什么 npm 的 exports 字段在打字稿中不起作用?

Why doesn't the exports field of npm work in typescript?

我们的库 @ltonetwork/lto 是用打字稿编写的。我们在lib文件夹中使用tsc编译为javascript

该包包含几个子包,它们位于包含 index.ts 文件的子文件夹中。

尝试导入子模块时,像这样

import {Transfer} from "@ltonetwork/lto/transactions";

我希望它能正常工作,但我收到以下错误

test.ts:1:24 - error TS2307: Cannot find module '@ltonetwork/lto/transactions' or its corresponding type declarations.

@ltonetwork/lto的package.json包含

{
  "scripts": {
    "compile": "tsc -p ./tsconfig.json"
  },
  "main": "lib",
  "exports": {
    ".": "./lib/index.js",
    "./*": "./lib/*/index.js",
    "./package.json": "./package.json"
  },
  "files": [
    "lib",
    "interfaces.d.ts"
  ]
}

而 tsconfig.json 是

{
  "compilerOptions": {
    "alwaysStrict": true,
    "baseUrl": "",
    "lib": ["es2017.object", "es2015", "es6", "dom"],
    "module": "commonjs",
    "sourceMap": true,
    "declaration": true,
    "target": "es6",
    "paths": {},
    "rootDir": "src",
    "outDir": "lib"
  },
  "include": ["src"]
}

我尝试明确命名子模块,而不是在 exports 中使用通配符,但这没有任何区别。

我做错了什么导致了这个导入问题?


编辑: 这与 monorepos 或 yarn 工作区无关。这是关于在带有 typescript 4.7.1-rc 的 npm 中使用 exports 字段。此功能不适用于早期版本的打字稿。

有关详细信息,请参阅 https://github.com/microsoft/TypeScript/issues/33079

我也试过了

{
  "scripts": {
    "compile": "tsc -p ./tsconfig.json"
  },
  "main": "lib",
  "exports": {
    ".": {
      "require": {
        "default": "./lib/index.js",
        "types": "./lib/index.d.ts"
      },
      "import": {
        "default": "./lib/index.js",
        "types": "./lib/index.d.ts"
      }
    },
    "./transactions": {
      "require": {
        "default": "./lib/transactions/index.js",
        "types": "./lib/transactions/index.d.ts"
      },
      "import": {
        "default": "./lib/transactions/index.js",
        "types": "./lib/transactions/index.d.ts"
      }
    },
    "./package.json": "./package.json"
  },
  "files": [
    "lib",
    "interfaces.d.ts"
  ]
}

确保 moduleResolution 在您的 tsconfig.json 文件中设置为 Node16NodeNext