打字稿模块增强是否会自动导出到组件库中?

Bas*_*sem 8 typescript reactjs material-ui module-augmentation

material-ui我在底层使用 Typescript 创建了一个组件库。我使用了 Typescript 模块增强来向主题添加新选项,如Typescript 文档的主题定制中所述。

// createPalette.d.ts/* eslint-disable @typescript-eslint/no-unused-vars */
import { Palette, PaletteOptions } from "@material-ui/core/styles/createPalette";
declare module "@material-ui/core/styles/createPalette" {
    interface Palette {
        highlight: PaletteColor;
        layout: LayoutPaletteColor;
    }
    interface PaletteOptions {
        highlight: PaletteColorOptions;
        layout?: LayoutPaletteColor;
    }
    interface LayoutPaletteColorOptions {
        paper: string;
        text: string;
    }

    interface SidebarPaletteColorOptions extends LayoutPaletteColorOptions {
        navItemSelectedBg: string;
        navItemSelectedColor: string;
    }
    interface LayoutPaletteColor {
        header: LayoutPaletteColorOptions;
        sidebar: SidebarPaletteColorOptions;
        footer: LayoutPaletteColorOptions;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,我构建我的项目并将其发布到 Github 包。我还使用这个脚本将*.d.ts文件复制到dist文件夹

"copy-typings": "copyfiles -u 1 \"./src/types/*.d.ts\" dist",

例如,当我在另一个项目中安装包并引用标头时,我收到此错误

Cannot read property 'header' of undefined它指向被theme.palette.layout.header.paper引用的行。

错误

这让我相信我的createPalette.d.ts组件仅对组件库本身有效,而当组件在另一个项目中使用时则无效。

如何导出这个模块增强?或者如何使这项工作有效?

小智 0

我想我已经找到了解决你问题的方法。

长话短说

  1. 您应该将您的d.ts文件或包含文件夹包含在package.json
...
files: [
  "dist",
  "src/types" or "src/types/global.d.ts"
]
...
Run Code Online (Sandbox Code Playgroud)
  1. 在您的中指定全局类型tsconfig.json
"types": ["node", "@YOUR_PACKAGE_NAME/src/types"]
Run Code Online (Sandbox Code Playgroud)

默认情况下,TS 包括文件夹中的全局定义文件@types。该"types"属性告诉它包含其他文件夹中的某些 d.ts 文件。我不知道它到底是如何工作的,但这解决了我的项目中完全相同的问题。

我的解释很差,但我希望你能明白)希望有帮助