在 NextJs 应用程序中,我想添加 <script>
代码,但没有得到在哪里添加以及如何添加?我尝试将其添加到 .js
文件,但无法识别。
在 react 中,我们有 index.html
要添加这些东西,在 Nextjs 应用程序中呢?
最佳答案
编辑index.html
, NextJS 中的等价物是 _document.js
file .
A custom Document is commonly used to augment your application's
<html>
and<body>
tags.
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>
</>
)
}
关于javascript - NextJs - 我们可以在哪里添加 <script> 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67189907/