網站搜尋

reactjs - 修復在使用 TypeScript 時 next.js 的 _document.tsx 中由 Document 和 ctx.renderPage =() 引發的 ESLint 警告


maxbause 很貼心地創建了一個漂亮的 Next.js 範本項目,該項目在 TypeScript 中包含 GraphQL 和 styled components。

https://github.com/maxbause/next-graphql-styled-components-ts-boilerplate/blob/master/pages/_document.tsx

然而,當我將 ESLint 添加到專案中時,我收到了幾個警告和錯誤,因為原因基本上是普通的 JavaScript。

我修好了大部分,但在 _document.tsx 文件中還有兩個警告讓我卡住了。

首先,我在 Document< any> 的 any 部分收到以下警告:「Unexpected any. Specify a different type.」(意外的 any。請指定不同的類型。)如果我移除 any 而不使用任何類型、或使用 unknown 或 never,則會在 this.props.styleTags 出現錯誤。

第二個問題是 Missing return type on function 警告,這個警告是由於在 ctx.renderPage =() => 中缺少返回類型引起的,這段程式碼緊跟在 try 之後,我不知道應該添加什麼。

我在 TypeScript 上有點新手,所以如果這個問題有明顯的解法,請不要對我太嚴苛。我查了很多資料,但還是無法弄清楚。

我知道我可以忽略甚至禁用這些錯誤,但如果我要禁用這些錯誤,我會感激你能解釋為什麼這麼做是合理的。

我希望這個問題對所有有興趣使用 Next.js 搭配 TypeScript 的人都有幫助。

_document.tsx (警告被拋出的地方)

import React from 'react';
import Document, { Head, Main, NextScript, DocumentContext, DocumentInitialProps } from 'next/document';
import { ServerStyleSheet } from 'styled-components';

export default class MyDocument extends Document<any> {
    static async getInitialProps(ctx: DocumentContext): Promise<DocumentInitialProps> {
        const sheet = new ServerStyleSheet();
        const originalRenderPage = ctx.renderPage;

        try {
            // wraps the collectStyles provider around our <App />.
            ctx.renderPage = () =>
                originalRenderPage({
                    enhanceApp: App => (props): React.ReactElement => sheet.collectStyles(<App {...props} />),
                });

            // extract the initial props that may be present.
            const initialProps = await Document.getInitialProps(ctx);

            // returning the original props together with our styled components.
            return {
                ...initialProps,
                styles: (
                    <>
                        {initialProps.styles}
                        {sheet.getStyleElement()}
                    </>
                ),
            };
        } finally {
            sheet.seal();
        }
    }

    render(): JSX.Element {
        return (
            <html>
                <Head>{this.props.styleTags /*rendering the actually stylesheet*/}</Head>
                <body>
                    <Main />
                    <NextScript />
                </body>
            </html>
        );
    }
}

.eslintrc.js

var OFF = 0, WARN = 1, ERROR = 2;

module.exports = {
    parser: '@typescript-eslint/parser', // Specifies the ESLint parser
    extends: [
        'plugin:react/recommended', // Uses the recommended rules from @eslint-plugin-react
        'plugin:@typescript-eslint/recommended', // Uses the recommended rules from the @typescript-eslint/eslint-plugin
        'prettier/@typescript-eslint', // Uses eslint-config-prettier to disable ESLint rules from @typescript-eslint/eslint-plugin that would conflict with prettier
        'plugin:prettier/recommended', // Enables eslint-plugin-prettier and eslint-config-prettier. This will display prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array.
    ],
    parserOptions: {
        ecmaVersion: 2018, // Allows for the parsing of modern ECMAScript features
        sourceType: 'module', // Allows for the use of imports
        ecmaFeatures: {
            jsx: true, // Allows for the parsing of JSX
        },
    },
    rules: {
        '@typescript-eslint/interface-name-prefix': [ERROR, {'prefixWithI': 'always'}]
        // Place to specify ESLint rules. Can be used to overwrite rules specified from the extended configs
        // e.g. "@typescript-eslint/explicit-function-return-type": "off",
    },
    settings: {
        react: {
            version: 'detect', // Tells eslint-plugin-react to automatically detect the version of React to use
        },
    },
};

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve"
  },
  "exclude": [
    "node_modules"
  ],
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx"
  ]
}

package.json

{
    "name": "killer-frontend",
    "version": "1.0.0",
    "main": "index.js",
    "license": "MIT",
    "dependencies": {
        "@apollo/react-hooks": "^3.1.3",
        "apollo-boost": "^0.4.7",
        "graphql": "^14.5.8",
        "next": "^9.1.6",
        "next-with-apollo": "^4.3.0",
        "node-fetch": "^2.6.0",
        "react": "^16.12.0",
        "react-dom": "^16.12.0",
        "styled-components": "^5.0.1"
    },
    "scripts": {
        "dev": "next",
        "build": "next build",
        "start": "next start",
        "lint": "tsc --noEmit && eslint '*/**/*.{js,ts,tsx}' --quiet --fix"
    },
    "devDependencies": {
        "@types/node": "^13.1.1",
        "@types/react": "^16.9.17",
        "@types/styled-components": "^5.0.1",
        "@typescript-eslint/eslint-plugin": "^2.23.0",
        "@typescript-eslint/parser": "^2.23.0",
        "babel-plugin-styled-components": "^1.10.7",
        "eslint": "^6.8.0",
        "eslint-config-prettier": "^6.10.0",
        "eslint-plugin-prettier": "^3.1.2",
        "eslint-plugin-react": "^7.19.0",
        "prettier": "^1.19.1",
        "typescript": "^3.7.4"
    }
}

答案#1

static getInitialProps({ renderPage }: DocumentContext): Promise<RenderPageResult> {
   return Promise.resolve<RenderPageResult>(renderPage())
}

對我有用

UPD,使用 styled-components

static async getInitialProps(ctx: DocumentContext): Promise<RenderPageResult> {
    const sheet = new ServerStyleSheet();
    const originalRenderPage = ctx.renderPage;
    const initialProps = await Document.getInitialProps(ctx);

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

      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        ),
      } as RenderPageResult;
    } catch {
      return initialProps;
    } finally {
      sheet.seal();
    }
  }

答案#2

希望它對你仍然有用。

編輯:我應該說明,我不確定這是否是正確的型別。不過這確實讓 TypeScript 的語法檢查器不再報錯,同時也沒有給它隱含的 any 型別。

ctx.renderPage = (): RenderPageResult | Promise<RenderPageResult> =>
    originalRenderPage({
            enhanceApp: (App) => (props): ReactElement =>
                sheet.collectStyles(<App {...props} />),
        });
    ```