📜  如何将 Material-UI 与 Next.js 一起使用?

📅  最后修改于: 2022-05-13 01:56:19.621000             🧑  作者: Mango

如何将 Material-UI 与 Next.js 一起使用?

在本文中,我们将学习一些额外的必要步骤,以将 Material-UI 与 Next.js 项目集成。

首先让我们从创建一个 Next.js 项目开始。

创建 Next.js 项目:在终端中运行以下命令

npx create-next-app gfg-next-mui

项目结构:它看起来像这样。

项目结构

安装 Material-UI:要安装依赖项并将它们保存在 package.json 文件中,请运行:

现在按照以下步骤操作:

第 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) => (