typescript - TS 将单独的类型文件导入单个 index.d.ts 文件

标签 typescript typescript-typings

我想将组件类型分成单独的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/

相关文章:

node.js - 未找到命令 : ts-node-dev

node.js - typescript 足够健壮吗?

javascript - 以 ES5 为目标时, typescript 编译输出 "import"

typescript - 如何将对象键的值映射到 TypeScript 中的同一对象?

node.js - 你能在 Typescript Compiler API 中引入 excludes/includes 选项吗?

将声明设置为 TRUE 时出现 typescript 错误

typescript - 如何在 type-graphql 中为联合类型执行字段解析器

typescript - gulp-typescript 和 typescript 的新@types 打字?

visual-studio - angular 2 - PrimeNg teamcity/visual Studio 编译失败(不包括 node_modules)

typescript - 如何在 Typescript 中编写严格要求其参数的函数类型