网站搜索

reactjs - 在 monorepo 中与每个包共享 TypeScript 模块


我有一个使用 styled-components 构建的 React 组件的单一仓库,它们的主题来自主题提供者。

declare module 'styled-components' {
  export interface DefaultTheme {
    colours: Colours;
    spacing: Spacing;
    breakpoints: Breakpoints;
  }
}

上述内容目前位于我的根类型文件夹 <root>/types/styled.d.ts

然而,我大约有20个组件包,而且还在增加。

当我在组件的 src 目录中包含上述文件时,我的 IntelliSense 能正常工作。

<root>/components/[component name]/src/[src files + styled.d.ts]

然而,在每个包中都包含相同的文件似乎有些过头?

有没有办法,也许可以使用 tsconfig?告诉我的包使用我根类型文件夹中的上述模块吗?

谢谢!

编辑:

我已更新我的文件以如下方式导入:import '@common-types/styled';

这按预期工作——这是做这个的正确方式吗?

答案#1

虽然我不确定什么是“理想”的方法,但你的问题帮我解决了一个类似的问题。

我正在做的是在声明 MyTheme 的同一个文件中包含声明(例如 <rootDir>/packages/theme/src/theme.ts)。

export type MyThemetype = {
  colors: {
    foreground: 'black' | 'white',
  }
}

declare module 'styled-components' {
  export interface DefaultTheme extends MyThemeType {}
}

MyThemeType 最终会在此包的 <rootDir>/packages/theme/src/index.ts 中导出(我们称它为 @my-lib/theme)。

然后我在其他以 @my-lib/theme 为依赖的包上使用它。

例如 <rootDir>/packages/label/...

import '@my-lib/theme'
import styled from 'styled-components'

const Label = styled.span`
  color: ${({ theme }) => theme.colors.foreground} // intellisense works as expected
`

export default Label

我相信这和你正在做的事情类似,所以谢谢你!

答案#2

在 monorepo 中的项目之间共享 declare module ***,我的解决方案

  1. 创建通用类型项目 aweb-types,添加以下 global.d.ts
import { pageLoading } from './src/loading/PageLoading'

declare module 'vue/types/vue' {
  interface Vue {
    $loading: typeof pageLoading
  }
}
  1. 因为我需要扩展 Vue 定义,所以我应该在 aweb-types 的 node_modules 中有 Vue
"peerDependencies": {
  "vue": "^2.7.16"
},
  1. 我可以在目标项目的 tsconfig.json 中使用这个 global.d.ts
// tsconfig.json
{
  "files": ["../../packages/aweb-types/global.d.ts"],
}

现在我可以在 vscode 中链接 this.$loading.show() 输入图片描述

相关文章