简体   繁体   English

如何使用 React 和 TypeScript 将实现与类型声明分开?

[英]How can I separate a implementations from type declarations with React and TypeScript?

Let's say I want to provide a React component type (Video in this example) that I can import from an "sdk" library and use in another TypeScript React component that lives in a different repo:假设我想提供一个 React 组件类型(本例中的视频),我可以从“sdk”库导入它并在另一个 TypeScript React 组件中使用,该组件位于不同的 repo 中:

import { Video } from "sdk";

export default function MyComponent {
  return (
    <Video src={...} />
  );
}

But I don't want the "sdk" library to contain the implementation for that component.但我不希望“sdk”库包含该组件的实现。 I want the "sdk" to export the type declaration, and I want to mount MyComponent inside a remote-component in another React app, which provides the implementation for everything in "sdk":我希望“sdk”导出类型声明,并且我想将 MyComponent 安装在另一个 React 应用程序的远程组件中,它为“sdk”中的所有内容提供实现:

import MyVideo from "../my-video";

resolve: {
  sdk: {
    Video: MyVideo,
  },
}

const requires = createRequires(resolve);
export const RemoteComponent = createRemoteComponent({ requires });

Is there a way I can write this sdk library that exports TypeScript types with no implementations, and then use that sdk in another repo with the expectation that the implementation will be available at runtime when the component is mounted?有没有一种方法可以编写这个 sdk 库,它导出没有实现的 TypeScript 类型,然后在另一个 repo 中使用该 sdk,期望在挂载组件时该实现在运行时可用? This would be similar to allowing for dynamic linking in C by providing header files in an SDK.这类似于通过在 SDK 中提供 header 文件来允许 C 中的动态链接。

Yes, many libraries originally written in JavaScript offer TypeScript definition files ( d.ts ).是的,许多最初在 JavaScript 中编写的库提供 TypeScript 定义文件 ( d.ts )。 Here's an example: https://github.com/vaadin/web-components/tree/23.3/packages/details/src .这是一个示例: https://github.com/vaadin/web-components/tree/23.3/packages/details/src

You can enable declaration emit in your tsconfig.json :您可以在tsconfig.json中启用声明发出:

{
  "compilerOptions": {
    "declaration": true
  }
}

This will cause the compiler to generate d.ts files.这将导致编译器生成d.ts文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM