首页 > 解决方案 > Next.js 使用样式化组件构建时返回错误_document.js

问题描述

我正在使用 _document.js 来确保 nextjs 将使用 styled-components 呈现页面(这解决了重新加载时的中断),但我遇到了错误。

我试图通过升级下一步、反应和金丝雀来解决它,但没有成功。

您可以在下面找到代码以及显示的错误。

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();
        }
    }
}

显示的错误:

./pages/_document.js
1:1  Error: next/document should not be imported outside of pages/_document.js. See https://nextjs.org/docs/messages/no-document-import-in-page.  @next/next/no-document-import-in-page
12:27  Error: Component definition is missing display name  react/display-name

info  - Need to disable some ESLint rules? Learn more here: https://nextjs.org/docs/basic-features/eslint#disabling-rules
error Command failed with exit code 1.

标签: next.jsstyled-components

解决方案


推荐阅读