在 NextJs 应用程序中,我想添加 <script>
代码但没有找到添加位置以及如何添加?我尝试将其添加到 .js
文件中,但无法识别。
在 React 中,我们有 index.html
来添加这些东西,那么在 Nextjs 应用程序中呢?
答案 0 :(得分:3)
要编辑 index.html
,NextJS 中的等效项是 _document.js
file。
自定义文档通常用于扩充应用程序的 <html>
和 <body>
标签。
import Document, { Html, Head, Main, NextScript } from 'next/document'
class MyDocument extends Document {
static async getInitialProps(ctx) {
const initialProps = await Document.getInitialProps(ctx)
return { ...initialProps }
}
render() {
return (
<Html>
<Head />
<body>
<Main />
<NextScript />
<script>...</script>
</body>
</Html>
)
}
}
如果您只想将元素附加到 <head>
标记(针对特定页面),请使用 next/head
:
import Head from 'next/head'
function IndexPage() {
return (
<>
<Head>
<script>....</script>
</Head>
</>
)
}