如何将 Material-UI 与 Next.js 一起使用?
在本文中,我们将学习一些额外的必要步骤,以将 Material-UI 与 Next.js 项目集成。
首先让我们从创建一个 Next.js 项目开始。
创建 Next.js 项目:在终端中运行以下命令
npx create-next-app gfg-next-mui
项目结构:它看起来像这样。
安装 Material-UI:要安装依赖项并将它们保存在 package.json 文件中,请运行:
npm install @mui/material @emotion/react @emotion/styled @emotion/server
现在按照以下步骤操作:
第 1 步:创建自定义文件/pages/_document.js并将以下代码添加到其中。
_document.js
import * as React from 'react';
import Document, { Html, Head, Main, NextScript } from 'next/document';
import createEmotionServer from '@emotion/server/create-instance';
import theme from '../src/theme';
import createEmotionCache from '../src/createEmotionCache';
export default class MyDocument extends Document {
render() {
return (
{/* PWA primary color */}
{/* Inject MUI styles first to match with the prepend: true configuration. */}
{this.props.emotionStyleTags}
);
}
}
// `getInitialProps` belongs to `_document` (instead of `_app`),
// it's compatible with static-site generation (SSG).
MyDocument.getInitialProps = async (ctx) => {
const originalRenderPage = ctx.renderPage;
// You can consider sharing the same emotion cache between
// all the SSR requests to speed up performance.
// However, be aware that it can have global side effects.
const cache = createEmotionCache();
const { extractCriticalToChunks } = createEmotionServer(cache);
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) =>
function EnhanceApp(props) {
return ;
},
});
const initialProps = await Document.getInitialProps(ctx);
// This is important. It prevents emotion to render invalid HTML.
// See
// https://github.com/mui-org/material-ui/issues/26561#issuecomment-855286153
const emotionStyles = extractCriticalToChunks(initialProps.html);
const emotionStyleTags = emotionStyles.styles.map((style) => (
));
return {
...initialProps,
emotionStyleTags,
};
};
Theme.js
import { createTheme } from '@mui/material/styles';
import { red } from '@mui/material/colors';
// Create a theme instance.
const theme = createTheme({
palette: {
primary: {
main: '#556cd6',
},
secondary: {
main: '#19857b',
},
error: {
main: red.A400,
},
},
});
export default theme;
createEmotionCache.js
import createCache from '@emotion/cache';
export default function createEmotionCache() {
return createCache({ key: 'css', prepend: true });
}
_app.js
import * as React from 'react';
import PropTypes from 'prop-types';
import Head from 'next/head';
import { ThemeProvider } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';
import { CacheProvider } from '@emotion/react';
import theme from '../src/theme';
import createEmotionCache from '../src/createEmotionCache';
// Client-side cache shared for the whole session
// of the user in the browser.
const clientSideEmotionCache = createEmotionCache();
export default function MyApp(props) {
const { Component, emotionCache =
clientSideEmotionCache, pageProps } = props;
return (
{/* CssBaseline kickstart an elegant,
consistent, and simple baseline to
build upon. */}
);
}
MyApp.propTypes = {
Component: PropTypes.elementType.isRequired,
emotionCache: PropTypes.object,
pageProps: PropTypes.object.isRequired,
};
index.js
import Head from "next/head";
import styles from "../styles/Home.module.css";
export default function Home() {
return (
Create Next App
Welcome to
Next.js! integrated with{" "}
Material-UI!
Get started by editing{" "}
pages/index.js
);
}
步骤 2:创建一个src文件夹,添加theme.js和createEmotionCache.js文件如下
主题.js
import { createTheme } from '@mui/material/styles';
import { red } from '@mui/material/colors';
// Create a theme instance.
const theme = createTheme({
palette: {
primary: {
main: '#556cd6',
},
secondary: {
main: '#19857b',
},
error: {
main: red.A400,
},
},
});
export default theme;
createEmotionCache.js
import createCache from '@emotion/cache';
export default function createEmotionCache() {
return createCache({ key: 'css', prepend: true });
}
第 3 步:使用以下代码更新文件/pages/_app.js
_app.js
import * as React from 'react';
import PropTypes from 'prop-types';
import Head from 'next/head';
import { ThemeProvider } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';
import { CacheProvider } from '@emotion/react';
import theme from '../src/theme';
import createEmotionCache from '../src/createEmotionCache';
// Client-side cache shared for the whole session
// of the user in the browser.
const clientSideEmotionCache = createEmotionCache();
export default function MyApp(props) {
const { Component, emotionCache =
clientSideEmotionCache, pageProps } = props;
return (
{/* CssBaseline kickstart an elegant,
consistent, and simple baseline to
build upon. */}
);
}
MyApp.propTypes = {
Component: PropTypes.elementType.isRequired,
emotionCache: PropTypes.object,
pageProps: PropTypes.object.isRequired,
};
第 4 步:使用以下代码更新文件/pages/index.js
index.js
import Head from "next/head";
import styles from "../styles/Home.module.css";
export default function Home() {
return (
Create Next App
Welcome to
Next.js! integrated with{" "}
Material-UI!
Get started by editing{" "}
pages/index.js
);
}
运行应用程序的步骤:要运行应用程序,请在终端中键入以下命令。
npm run dev
输出: