【发布时间】:2021-12-12 05:01:11
【问题描述】:
暴露节点包模块的标准方法是在 index.ts 中列出它们,如下所示:
export * from './module1';
export * from './module2';
但是,这会立即加载两个模块的内容。我想要一个未在 index.ts 文件中导出的模块,因为它需要安装一些可选的依赖项。
我遵循了这个指南:https://blog.mozilla.org/data/2021/04/07/this-week-in-glean-publishing-glean-js/
我的 package.json:
"exports": {
".": {
"import": "./dist/es/index.js",
"require": "./dist/cjs/index.js"
},
"./module2": {
"import": "./dist/es/module2.js",
"require": "./dist/cjs/module2.js"
}
},
"typesVersions": {
"*": {
".": [
"./dist/types/index.d.ts"
],
"./module2": [
"./dist/types/module2.d.ts"
]
}
},
// fallback for older Node versions:
"module": "dist/es/index.js",
"main": "dist/cjs/index.js",
"types": "dist/types/index.d.ts",
在我构建项目后(使用tsc,分别用于 CJS 和 ESM),输出目录结构如下所示:
- dist
- cjs
- index.js
- module2.js
- es
- index.js
- module2.js
- types
- index.d.ts
- module2.d.ts
但是,当我发布这个包并在客户端项目中安装它时,module2 不起作用。
import {sayHello} from 'ts-exports-test';
import {sayGoodbye} from 'ts-exports-test/module2';
console.log(sayHello());
console.log(sayGoodbye());
我使用ts-node 运行它,但出现错误:
src/index.ts:2:26 - error TS2307: Cannot find module 'ts-exports-test/module2' or its corresponding type declarations.
注意:对于使用 TS 4.5 的客户端,可以在“exports”部分声明类型路径,从而不需要“typesVersions”破解。但这是为了未来。
【问题讨论】:
-
我试图重现该问题,但它对我有用。你能检查一下这个 repo 并检查你的配置是否有任何区别github.com/diedu89/ts-export-import-test
-
感谢您尝试复制它。但是,在您的示例中,客户端中的
ts-exports-test/module2导入解析为包主目录中的module2.ts文件,而不是dist/types/module2.d.ts(根据WebStorm)。如果通过将"files": ["dist"]添加到 package.json 来从输出包中删除源文件,或者将源文件移动到src目录,则将不起作用。
标签: typescript node-modules es6-modules commonjs