为什么在TypeScript中npm的导出字段(exports field)不起作用?

16 浏览
0 Comments

为什么在TypeScript中npm的导出字段(exports field)不起作用?

我们的库@ltonetwork/lto是用typescript编写的。我们使用tsc将其编译为位于lib文件夹中的javascript文件。\n该包含有几个子包,它们位于包含index.ts文件的子文件夹中。\n当尝试导入一个子模块时,像这样\n

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

\n我期望它可以工作,但是却出现以下错误\n

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

\n@ltonetwork/lto的package.json包含以下内容\n{\n \"scripts\": {\n \"compile\": \"tsc -p ./tsconfig.json\"\n },\n \"main\": \"lib\",\n \"exports\": {\n \".\": \"./lib/index.js\",\n \"./*\": \"./lib/*/index.js\",\n \"./package.json\": \"./package.json\"\n },\n \"files\": [\n \"lib\",\n \"interfaces.d.ts\"\n ]\n}\n\n而tsconfig.json是这样的\n{\n \"compilerOptions\": {\n \"alwaysStrict\": true,\n \"baseUrl\": \"\",\n \"lib\": [\"es2017.object\", \"es2015\", \"es6\", \"dom\"],\n \"module\": \"commonjs\",\n \"sourceMap\": true,\n \"declaration\": true,\n \"target\": \"es6\",\n \"paths\": {},\n \"rootDir\": \"src\",\n \"outDir\": \"lib\"\n },\n \"include\": [\"src\"]\n}\n\n我尝试过在exports中明确命名子模块,而不是使用通配符,但没有任何区别。\n导致这个导入问题的错误是什么?\n


\n编辑:\n这与monorepos或yarn工作区无关。这是关于在typescript 4.7.1-rc中使用npm的exports字段的问题。在较早的typescript版本中,这个功能是无效的。\n更多信息请参见https://github.com/microsoft/TypeScript/issues/33079\n我还尝试过\n{\n \"scripts\": {\n \"compile\": \"tsc -p ./tsconfig.json\"\n },\n \"main\": \"lib\",\n \"exports\": {\n \".\": {\n \"require\": {\n \"default\": \"./lib/index.js\",\n \"types\": \"./lib/index.d.ts\"\n },\n \"import\": {\n \"default\": \"./lib/index.js\",\n \"types\": \"./lib/index.d.ts\"\n }\n },\n \"./transactions\": {\n \"require\": {\n \"default\": \"./lib/transactions/index.js\",\n \"types\": \"./lib/transactions/index.d.ts\"\n },\n \"import\": {\n \"default\": \"./lib/transactions/index.js\",\n \"types\": \"./lib/transactions/index.d.ts\"\n }\n },\n \"./package.json\": \"./package.json\"\n },\n \"files\": [\n \"lib\",\n \"interfaces.d.ts\"\n ]\n}\n

0
0 Comments

为什么 TypeScript 中的 npm 的 exports 字段不起作用?

自 TypeScript 3.1 开始,我们可以这样做,并且不需要使用者有一个 tsconfig.json 文件。

"typesVersions": {

"*": {

"path1": [ "./path/to/path1.d.ts" ],

"path2": [ "./path/to/path2.d.ts" ],

}

},

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

0
0 Comments

为什么在TypeScript中,npm的exports字段不起作用?

在使用TypeScript的项目中,如果遇到npm的exports字段不起作用的问题,可以尝试以下解决方法:

1. 确保消费库中的tsconfig.json文件中的moduleResolution设置为Node16NodeNext

2. 或者尝试使用bundler选项。

3. 如果只有导入库中的每个导入都出现此错误,请确保库的用户都指定了这些设置。在编写库本身时,不需要使用这些设置,但也不会有害。

另外,如果添加了moduleResolution后问题仍然存在,可以尝试在每个导入中添加.js扩展名。

在TypeScript项目中遇到npm的exports字段不起作用的问题时,可以通过设置moduleResolutionbundler选项来解决。同时,对于每个导入,可能需要添加.js扩展名。

0