【发布时间】:2020-09-19 15:04:57
【问题描述】:
我安装了模块foo,它有这个package.json:
{
"name": "foo",
"version": "0.0.1",
"exports": {
".": ["./index.js"]
},
"types": "./index.d.ts"
}
foo 带有自己的模块入口点类型。但是,我需要从foo 导入bar.js。因为它没有在index.js 中导出,所以我必须这样做:
import {bar} from './node_modules/foo/bar'
这是因为如果我使用import bar from 'foo/bar',我会收到错误Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './bar' is not defined by "exports" in /path/to/project/node_modules/foo/package.json。
我这样输入了foo/bar:
export const bar: 'bar'
我应该把这个文件放在哪里,我需要把什么放在我的tsconfig.json 中?
我已经尝试将我的类型输入 ./types/foo/bar.d.ts 并在我的 tsconfig compilerOptions 中使用 "typeRoots": ["node_modules/@types", "./types"],但 TS 找不到我的声明文件:
Could not find a declaration file for module './node_modules/foo/bar'. '/path/to/project/node_modules/foo/bar.js' implicitly has an 'any' type.
我也试过/// <reference types="./types/foo/bar" />,但同样的错误仍然存在。
如果我不是从 npm 模块键入文件,我会直接将类型放入 ./node_modules/foo/bar.d.ts,但我不想手动将任何内容放入 node_modules。
【问题讨论】:
-
丑陋的解决方案,但可能有效 - 转到包并检查所需类型是否真的存在。将其从那里复制到名为 typings.d.ts 的项目的根目录中,在您的 tsconfig.json 中添加新条目到类型数组中:“./typings”
-
@Drag13 我需要的类型不在包的类型中,所以这行不通。
-
检查 @types/
以获取您需要的类型。无论如何,您至少需要一些类型。或者你必须自己写。 -
@Drag13 我正在编写一个库,它使用了一些不打算导出的包内部的东西,所以我为我需要的文件编写了自己的类型。
标签: typescript node-modules .d.ts