sin*_*ari 2 javascript reactjs next.js
在大多数示例中,要禁用预取,他们通过禁用特定的预取链接来实现,请参阅以下示例:
<Link href="/about" prefetch={false}>
<a>About us</a>
</Link>
Run Code Online (Sandbox Code Playgroud)
我想将整个项目的预取设置为 false。next.config.js 文件中有此设置吗?
我该怎么做?
不幸的是,Next.js 不支持disable
全局预取。
prefetch={false}
我们使用的所有<Link />
地方'next/link'
。/**
* Based on the docs at https://nextjs.org/docs/api-reference/next/link, the
* only way to disable prefetching is to make sure every <Link /> has <Link
* prefetch={false} />
*
* We don't want to create a wrapper Component or go around changing every
* single <Link />, so we use this Babel Plugin to add them in at build-time.
*/
module.exports = function (babel) {
const { types: t } = babel
return {
name: 'disable-link-prefetching',
visitor: {
JSXOpeningElement(path) {
if (path.node.name.name === 'Link') {
path.node.attributes.push(
t.jSXAttribute(
t.jSXIdentifier('prefetch'),
t.JSXExpressionContainer(t.booleanLiteral(false)),
),
)
}
},
},
}
}
Run Code Online (Sandbox Code Playgroud)
{
"presets": ["next/babel"],
"plugins": ["./babel/disable-nextjs-link-prefetching"]
}
Run Code Online (Sandbox Code Playgroud)
创建一个自定义链接组件并使用prefetch={false}
它并使用它而不是next/link
直接使用。
import Link from 'next/link'
export default function MyLink(props) {
// defaults prefetch to false if `prefetch` is not true
return <Link {...props} prefetch={props.prefetch ?? false}>
}
Run Code Online (Sandbox Code Playgroud)