Next.js typescript customize Document error: TypeError: Class constructor Document cannot be invoked without 'new'

Viewed 990

I have a website that included a customized Document by _document.js. But when I ran yarn dev I got

TypeError: Class constructor Document cannot be invoked without 'new'

I search for solutions for a long time and read many solutions but they talk about preset-env inside .babelrc. I don't have any babel config file.

experimentaly when i change "target": "es5" to "target": "es5" it was fixed. i don't want to use es6 in my tsconfig.

what should I do? (I am a newbie in next.js but I am fluent with js and react.js)

UPDATE

This is my _document.tsx:

import Document, {
    Html,
    Head,
    Main,
    NextScript,
    DocumentContext,
} from 'next/document'
import settings from '../utils/settings/settings'

class MyDocument extends Document {
    render() {
        return (
            <Html lang="fa">
                <Head>
                    <script
                        async
                        src={`https://www.googletagmanager.com/gtag/js?id=${settings.TRACKING_ID}`}
                    />

                    <script
                        dangerouslySetInnerHTML={{
                            __html: `
              window.dataLayer = window.dataLayer || [];
              function gtag(){dataLayer.push(arguments);}
              gtag('js', new Date());
              gtag('config', '${settings.TRACKING_ID}', { page_path: window.location.pathname });
            `,
                        }}
                    />
                </Head>
                <body dir="rtl">
                    <Main />
                    <NextScript />
                    <>
                        {/* Google Tag Manager */}
                        <script
                            dangerouslySetInnerHTML={{
                                __html: `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
                new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
                j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
                'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
                })(window,document,'script','dataLayer','${settings.GTM_ID}');`,
                            }}
                        />
                        {/* End Google Tag Manager */}
                        {/* Google Tag Manager (noscript) */}
                        <noscript
                            dangerouslySetInnerHTML={{
                                __html: `<iframe src="https://www.googletagmanager.com/ns.html?id=${settings.GTM_ID}" height="0" width="0" style="display:none;visibility:hidden"></iframe>`,
                            }}
                        />
                        {/* End Google Tag Manager (noscript) */}
                    </>
                </body>
            </Html>
        )
    }
}

export default MyDocument

This is my 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"
    },
    "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
    "exclude": ["node_modules"]
}

2 Answers

I used fork-ts-checker-webpack-plugin for several reasons like checking types before build and other pros that are mentioned in its document hence when I remove it the problem was solved.

I had a similar issue. Try the first piece of code and save file as a regular .js file.

I got this from the Next tutorial, with TypeScript and remembered after I encountered it in another project.

//your imports //

class MyDocument extends Document {
  //try this piece 
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx);
    return { ...initialProps };
  }



// Your code //
}

export default MyDocument
Related