【问题标题】:Cannot re-export a type when using the --isolatedModules with TS 3.2.2将 --isolatedModules 与 TS 3.2.2 一起使用时无法重新导出类型
【发布时间】:2019-05-12 16:26:21
【问题描述】:

我可能需要重新考虑我们构建 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 本身不会再转译代码。

如何在没有单独的导入语句转到 @/Component/types 的情况下重新导出它(这实际上可能是更简单的方法)?

【问题讨论】:

    标签: typescript webpack webpack-4


    【解决方案1】:

    我个人使用相同的结构,并在转到强制执行isolatedModulescreate-react-app 样板后偶然发现了相同的问题。与isolatedModules 背后的想法形成鲜明对比的解决方法是在index.ts 中使用export * from "./Component";

    【讨论】:

      【解决方案2】:

      TS 3.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 了解可能的扩展表格和建议。


      TS 3.7 或更早版本

      在以前的版本中,以下是不可能的:

      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"
      

      【讨论】:

      • 注意:以上功能在 Babel 中支持以v7.9.0开头
      猜你喜欢
      • 2023-01-14
      • 2020-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-12
      • 1970-01-01
      • 2018-06-04
      • 2019-10-19
      相关资源
      最近更新 更多