next.js: import customized Document from library causes 'Constructor invoked without 'new'' error
Bug report
- Make a library which included a customized Document(_document.js).
- 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

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)
I just took a deeper look at this.
The reason this issue is happening is because
nextmust be compiled by webpack.When you import it indirectly in
next-mui-helper(which is not bundled, as it’s innode_modules), webpack doesn’t get the chance to bundle or compilenext/**. 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-helperis compiled by webpack and not externalized, such thatnextimports 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-envfrompresetsin my .babelrc file and I am no longer receiving this error.In retrospect, not really sure why we had
@babel/preset-envin there. EDIT: Our project has a custom_documentand custom_app, but we don’t export it to other projects.I don’t have
.babelrcand mytsconfig.jsonis:when i changed
"target": "es5"to"target": "es6"it was fixed but I don’t want to change it toes6. what can I do?+1 I don’t use
@babel/envand I experience this issue. I had to downgrade to9.0.2.@thundermiracle it wasn’t any specific PR, these changes have been made across many PRs as we optimize Next.js’ core.