next.js: import customized Document from library causes 'Constructor invoked without 'new'' error

Bug report

  1. Make a library which included a customized Document(_document.js).
  2. import the customized Document into another project. throws TypeError: Class constructor Document cannot be invoked without 'new' error.

There’s no error before next9

To Reproduce

https://github.com/thundermiracle/next-lib-bug

Screenshots

image

System information

  • OS: [Windows]
  • Browser (if applies) [chrome,]
  • Version of Next.js: [9.0.2 and canary]

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 11
  • Comments: 21 (10 by maintainers)

Most upvoted comments

I just took a deeper look at this.

The reason this issue is happening is because next must be compiled by webpack.

When you import it indirectly in next-mui-helper (which is not bundled, as it’s in node_modules), webpack doesn’t get the chance to bundle or compile next/**. This package then just gets handled with typical Node imports.

To solve this, you’ll need to customize your webpack configuration to ensure that next-mui-helper is compiled by webpack and not externalized, such that next imports are properly seen by the build.

Do note that this extension of Document is not a supported behavior and is very prone to break release-by-release.

Note: I had this error this morning when upgrading to 9.0.3, but removed @babel/preset-env from presets in my .babelrc file and I am no longer receiving this error.

{
  "presets": [
-    "@babel/preset-env",
    "next/babel",
  ],
  "compact": true,
...(other config options for styled components, etc)

In retrospect, not really sure why we had @babel/preset-env in there. EDIT: Our project has a custom _document and custom _app, but we don’t export it to other projects.

I don’t have .babelrc and my tsconfig.json is:

{
    "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", ".next"]
}

when i changed "target": "es5" to "target": "es6" it was fixed but I don’t want to change it to es6. what can I do?

+1 I don’t use @babel/env and I experience this issue. I had to downgrade to 9.0.2.

@thundermiracle it wasn’t any specific PR, these changes have been made across many PRs as we optimize Next.js’ core.