繁体   English   中英

为什么 npm 的导出字段在 typescript 中不起作用?

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

我们的库@ltonetwork/lto是用 typescript 编写的。 我们使用tsc编译成lib文件夹下的javascript。

package 包含几个子包,它们位于包含 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 或纱线工作区无关。 这是关于使用 npm 中的exports字段和 typescript 4.7.1-rc。 此功能不适用于早期版本的 typescript。

有关详细信息,请参阅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"
  ]
}

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

自 Typescript 3.1 以来,我们已经能够做到这一点,并且不需要消费者拥有tsconfig.json

"typesVersions": {
    "*": {
        "path1": [ "./path/to/path1.d.ts" ],
        "path2": [ "./path/to/path2.d.ts" ],        
    }
},

这可能仅适用于命名子模块。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM