在大多数示例中,为了禁用预取,它们通过禁用用于预取的特定链接来禁用预取,请参见以下示例:
<Link href="/about" prefetch={false}>
<a>About us</a>
</Link>我想将整个项目的预取设置为false。在next.config.js文件中有此设置吗?
我该怎么做?
发布于 2022-10-12 08:22:44
不幸的是,在Next.js中,它不支持全局disable预取。
第一个解决办法
prefetch={false},我们从'next/link'中使用<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)),
),
)
}
},
},
}
}{
"presets": ["next/babel"],
"plugins": ["./babel/disable-nextjs-link-prefetching"]
}第二个解决办法
创建一个自定义链接组件,并为此使用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}>
}https://stackoverflow.com/questions/74038516
复制相似问题