如何在package.json中使用"exports"来处理嵌套子模块和TypeScript?

19 浏览
0 Comments

如何在package.json中使用"exports"来处理嵌套子模块和TypeScript?

我想利用 Node.js/`package.json` 中新近加入的 "exports" 功能,以便能够实现以下操作:

"exports": {

".": "./dist/index.js",

"./foo": "./dist/path/to/foo.js"

}

用户可以这样使用:

import { foo } from 'my-package/foo';

尽管 TypeScript 4.5 应该支持 "exports" 字段,但似乎并没有生效。我正在使用 TS 4.5.2 构建一个简单的包,并在使用 TS 4.5.2 的项目中使用该包。我查看了其他的 SO 问题、问题和这个 Github 线程以及这个 bug 报告,但似乎无法找到关于这个问题的共识以及它是否应该在当前环境下工作。

我仍然可以使用更冗长的语法进行导入:

import { foo } from 'my-package/dist/path/to/foo.js';

我还尝试了对象表示法的导出方式,但没有成功:

"exports": {

".": { "require": "./dist/index.js", "import": "./dist/index.js" },

"./foo": { "require": "./dist/path/to/foo.js", "import": "./dist/path/to/foo.js" }

}

这个功能在今天是否可以在 TypeScript 项目中使用?如果是,我漏掉了什么?有关源项目和消费项目的 tsconfig 的细节对于解决问题会很有帮助。TS 编译器会对 `module` 或 `moduleResolution` 字段使用 `node12` 或 `nodenext` 进行警告(我确实使用了 TS 4.5.2)。

0