我想将组件类型分成单独的index.d.ts
然后将这些类型导入最终的 index.d.ts
在我的 src 文件夹下。如何将这些类型导入单个 index.d.ts
没有得到错误[ts] Import or export declaration in an ambient module declaration cannot reference module through relative module name.
?
文件:
src
|__components
| |__Text
| |__index.js
| |__index.d.ts
| |__Button
| |__index.js
| |__index.d.ts
|__index.js
|__index.d.js
src/index.d.ts
declare module "my-module-name" {
export { default as Text } from "./components/Text/index.d.ts";
}
src/index.js
export { default as Text } from "./components/Text";
export { default as Button } from "./components/Button";
最佳答案
您不需要使用 declare module
.无论如何,相对路径在那里不起作用——它们只能用于模块扩充,即当您修改现有定义时。
首先在各自的文件夹中声明您的组件。我只用了React.ComponentType
,但你可以更具体。
./src/components/Button/index.d.ts
import * as React from 'react';
declare const Button: React.ComponentType;
export default Button;
./src/components/Text/index.d.ts
import * as React from 'react';
declare const Text: React.ComponentType;
export default Text;
接下来,创建一个桶文件以重新导出您的组件。
./src/index.d.ts
export { default as Text } from './components/Text'
export { default as Button } from './components/Button'
现在您的组件可以从
./src
访问。并从他们各自的文件夹中。如果我们创建了另一个名为 consumer
的目录在项目的根目录中,它可以访问您的组件:./consumer/index.ts
/**
* Import the re-exported components from `./src/index.d.ts`:
*/
import { Button } from '../src/';
/**
* Or import from their respective folders:
*/
import Text from '../src/components/Text';
请记住,以这种方式解析路径需要设置
"moduleResolution"
至"node"
在您的 tsconfig.json
.{
"compilerOptions": {
"baseUrl": ".",
"moduleResolution": "node"
}
}
关于typescript - TS 将单独的类型文件导入单个 index.d.ts 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54030107/