我可能需要重新考虑构造React组件的方式。我们正在使用允许使用Typescript的最新react-scripts,默认情况下,启用了isolatedModules
,这目前使我有些烦恼。
我们过去通常是这样构造组件的:
Component
|_ Component.tsx
|_ index.ts
|_ types.ts
Component.tsx
保留了没有声明的实际组件 index.ts
只是重新导出所有内容,因此我们可以使用单个入口点,并且可以执行类似import Component, { ComponentType } from '@/Component';
types.ts
保留实际的类型定义,并导出其中的大部分或全部。
到目前为止,一切都很好,并且在没有isolatedModules
的情况下也可以使用。但是,我们还导出了一些类型定义,从而有效地重新导出了Component/types.ts
中指定的接口。这将无法正常工作,因为TypeScript本身不会再转换代码。
如何在没有单独的import语句进入@/Component/types
的情况下重新导出它(无论如何,这实际上可能是更简单的方法)?
答案 0 :(得分:8)
您可以将type-only imports and exports与--isolatedModules
一起使用:
// types.ts
export type MyType = { a: string; b: number; };
// main.ts
// named import/export
import type { MyType } from './types'
export type { MyType }
// re-export
export type { MyType } from './types'
// namespace import
import type * as MyTypes from "./types";
export type RenamedType = MyTypes.MyType;
export { MyTypes };
// ^ Note the "type" keyword in statements above
Example Playground;查看PR,了解可能的扩展形式和建议。
在以前的版本中,不可能进行以下操作:
import { MyType } from './types';
export { MyType }; // error: Cannot re-export a type with --isolatedModules
export { MyType } from "./types"; // error, like above
类型重新导出必须使用workaround:
import { MyType as MyType_ } from "./types";
export type MyType = MyType_;
// or
export * from "./types"
答案 1 :(得分:1)
我个人使用的是同一结构,在移至强制执行create-react-app
的{{1}}样板之后,偶然发现了同一问题。似乎与isolatedModules
背后的想法形成鲜明对比的一种变通办法是在isolatedModules
中使用export * from "./Component";
。