我有一个网站,其中包含 _document.js 的自定义文档。但是当我运行 yarn dev
时,我得到了
TypeError: Class constructor Document cannot be invoked without 'new'
我搜索了很长时间的解决方案并阅读了很多解决方案,但他们都在谈论.babelrc
中的preset-env
。我没有任何 babel 配置文件。
当我将 "target": "es5"
更改为 "target": "es5"
时,它已被修复。我不想在我的 tsconfig 中使用 es6
。
我该怎么办? (我是 next.js
的新手,但我精通 js
和 react.js
)
更新
这是我的 _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
这是我的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"]
}
最佳答案
我使用 fork-ts-checker-webpack-plugin
有几个原因,比如在构建之前检查类型,以及它的文档中提到的其他优点,因此当我删除它时,问题就解决了。
关于typescript - Next.js typescript自定义文件报错: TypeError: Class constructor Document cannot be invoked without 'new' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68190473/