如何在 next.config.js 中完全禁用预取 | Next.js 中的数据预取

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 文件中有此设置吗?

我该怎么做?

Min*_*ina 8

不幸的是,Next.js 不支持disable全局预取。

第一个解决方法

  1. 在您的项目本地创建一个 Babel 插件,它将添加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)
  1. 添加/修改 ./.babelrc 以加载本地插件:
{
  "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)

资源