能否在Deno Fresh应用中使用Material UI组件?
如何在Deno Fresh框架中集成Material UI
当然可以实现,下面是实用的步骤和示例:
核心思路
Fresh是基于Deno的服务端渲染框架,Material UI(MUI)以客户端React组件为主,集成的关键是处理客户端 hydration 和MUI的样式注入逻辑。
具体实现步骤及示例
1. 初始化Fresh项目
先创建基础的Fresh项目:
deno run -A -r https://fresh.deno.dev my-mui-fresh-app cd my-mui-fresh-app
2. 配置MUI依赖
在项目根目录的import_map.json中添加MUI相关包:
{ "imports": { "$fresh/": "https://deno.land/x/fresh@1.6.8/", "preact": "https://esm.sh/preact@10.19.6", "preact/": "https://esm.sh/preact@10.19.6/", "@mui/material/": "https://esm.sh/@mui/material@5.15.10/", "@mui/icons-material/": "https://esm.sh/@mui/icons-material@5.15.10/", "@emotion/react": "https://esm.sh/@emotion/react@11.11.3", "@emotion/styled": "https://esm.sh/@emotion/styled@11.11.0" } }
3. 创建MUI客户端包装组件
在components/MuiProvider.tsx中编写用于包裹应用的Provider组件,处理样式缓存和主题配置:
import { useState, useEffect } from "preact/hooks"; import { ThemeProvider, createTheme } from "@mui/material/styles"; import CssBaseline from "@mui/material/CssBaseline"; import { CacheProvider } from "@emotion/react"; import createCache from "@emotion/cache"; export default function MuiProvider({ children }) { const [cache, setCache] = useState(null); useEffect(() => { const newCache = createCache({ key: "mui-style" }); setCache(newCache); }, []); if (!cache) return null; const theme = createTheme({ palette: { mode: "light", primary: { main: "#1976d2", }, }, }); return ( <CacheProvider value={cache}> <ThemeProvider theme={theme}> <CssBaseline /> {children} </ThemeProvider> </CacheProvider> ); }
4. 在Fresh应用中接入MUI
修改routes/_app.tsx,用上面的Provider包裹整个应用:
import { AppProps } from "$fresh/server.ts"; import MuiProvider from "../components/MuiProvider.tsx"; export default function App({ Component, pageProps }: AppProps) { return ( <MuiProvider> <Component {...pageProps} /> </MuiProvider> ); }
然后在routes/index.tsx中直接使用MUI组件:
import { Button, Typography, Box } from "@mui/material"; import { AddCircle } from "@mui/icons-material"; export default function Home() { return ( <Box sx={{ padding: 4, display: "flex", flexDirection: "column", gap: 2 }}> <Typography variant="h4" component="h1" gutterBottom> Fresh + Material UI 集成示例 </Typography> <Button variant="contained" startIcon={<AddCircle />}> 点击测试 </Button> </Box> ); }
5. 启动项目验证
运行命令启动项目,查看MUI组件是否正常渲染:
deno task start
注意事项
- Fresh使用Preact而非React,部分复杂MUI组件可能需要适配,但基础组件均可正常工作
- 服务端渲染时,样式缓存和主题Provider的配置是保证样式正确注入的关键
- 若遇到依赖兼容问题,可在
import_map.json中指定更具体的版本号
内容的提问来源于stack exchange,提问作者Some random IT boy
相关产品推荐
相关产品推荐

