You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js使用styled-components配置_document.js出现构建报错如何解决

报错1:@next/next/no-document-import-in-page

先确认你的_document.js文件存放路径是否为项目根目录下的pages/_document.js,不能放在app目录、pages的子目录或者其他自定义目录下。
如果路径确认无误属于ESLint误判,直接在文件顶部添加注释禁用该规则即可:

/* eslint-disable @next/next/no-document-import-in-page */

报错2:react/display-name

该报错是因为enhanceApp配置中返回的是匿名函数组件,没有设置显示名称,你可以选择把匿名函数改为命名函数修复,也可以直接禁用对应ESLint规则。

修改后完整可运行代码

/* eslint-disable @next/next/no-document-import-in-page */
/* eslint-disable react/display-name */
import Document from 'next/document';
import { ServerStyleSheet } from 'styled-components';

export default class MyDocument extends Document {
    static async getInitialProps(ctx) {
        const sheet = new ServerStyleSheet();
        const originalRenderPage = ctx.renderPage;

        try {
            ctx.renderPage = () =>
                originalRenderPage({
                    enhanceApp: (App) => (props) =>
                        sheet.collectStyles(<App {...props} />),
                });

            const initialProps = await Document.getInitialProps(ctx);
            return {
                ...initialProps,
                styles: (
                    <>
                        {initialProps.styles}
                        {sheet.getStyleElement()}
                    </>
                ),
            };
        } finally {
            sheet.seal();
        }
    }
}

上述禁用ESLint规则的操作不会影响styled-components服务端渲染的功能逻辑,也不会带来额外隐患。

内容的提问来源于stack exchange,提问作者Gabriel Panegrossi Santos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 14:15:01