英文:
Why does my TSC keep crashing when using MUI props
问题
这是一个关于将Next.js和Material UI JavaScript项目转换为TypeScript的问题。下面是您提供的代码示例,当我将Props
指定为交叉类型(与MUI的BoxProps
一起)时,TSC会冻结,并且实时类型检查似乎停止:
import { Box, BoxProps, SxProps } from '@mui/material';
type Props = {
onSubmit: (e: React.FormEvent) => void;
children: React.ReactNode;
sx: SxProps;
} & BoxProps;
// 这行似乎导致了冻结
export const Form = ({ onSubmit, ...props }: Props) => {
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
onSubmit(e);
};
return (
<Box
component="form"
onSubmit={handleSubmit}
{...props}
/>
);
}
这是我卡住的错误消息:
感谢任何帮助。
编辑:我已经注意到,如果我排除SxProps
,它可以正常工作。然而,当这两者一起在交叉类型中使用时...
英文:
I am currently converting a Next.js and Material UI JavaScript project to TypeScript.
Here is the code for one of my components, and whenever I specify Props
as an intersection type (with MUI's BoxProps
), the TSC freezes and live type-checking seems to stop:
import { Box, BoxProps, SxProps } from '@mui/material'
type Props = {
onSubmit: (e: React.FormEvent) => void
children: React.ReactNode
sx: SxProps
} & BoxProps
// 👆 seems to be causing freezing
export const Form = ({ onSubmit, ...props }: Props) => {
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
onSubmit(e)
}
return (
<Box
component="form"
onSubmit={handleSubmit}
{...props}
/>
)
}
Here's the error message thatI get stuck with:
Any help is appreciated.
EDIT: I've sinced noticed that it works fine if I exclude SxProps
. When the two are used in the intersection type together, on the other hand... 🤔
答案1
得分: 1
我在一个非常庞大的 monorepo 项目上使用 MUI 时遇到了类似的问题。这个错误只会在 development
环境中出现,而不会在 production
环境中出现。它是由于你导入 MUI 组件的方式引起的。
当你像这样使用 tree shaking
导入 MUI 组件时会发生什么
import { Box, BoxProps } from '@mui/material'
现在它会加载所有的 MUI 模块,并从中选择 Box
和 BoxProps
。这会导致 TypeScript 编译器有时冻结或变得更慢。
正如你可以在MUI文档中查看的那样。第一行说:
开发包可以包含整个库,这可能会导致启动时间较慢
👉 因此建议使用 path imports
而不是 tree shaking
import Box, { BoxProps } from '@mui/material/Box'
希望对你有所帮助。
英文:
I faced a similar issue when using MUI on a really huge monorepo project. This error will be only in development
environment and not in production
environment. It is caused by the way you are importing MUI components.
What is happening here when you import MUI component using tree shaking
like this
import { Box, BoxProps} from '@mui/material'
Now it loads all the MUI modules and picks up Box
and BoxProps
out of it. Which makes the typescript compiler to freeze or slower some times.
As you can check here in MUI docs. First line says,
> Development bundles can contain the full library which can lead to
> slower startup times
👉 So it is advised to use path imports
instead of tree shaking
import Box, { BoxProps } from '@mui/material/Box'
I hope it helps.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论