我知道Gatsby使用代码拆分来优化每个给定页面的包,但是当将页面创建为单页面应用程序时(如Client-only routes中提到的),我们将如何处理它。
如果我有一个像这样的app.js
(摘自example):
import React from "react"
import { Router } from "@reach/router"
import Layout from "../components/Layout"
import Details from "../components/Details"
import Home from "../components/Home"
import Login from "../components/Login"
import PrivateRoute from "../components/PrivateRoute"
import Status from "../components/Status"
const App = () => (
<Layout>
<Status />
<Router>
<PrivateRoute path="/app/profile" component={Home} />
<PrivateRoute path="/app/details" component={Details} />
<Login path="/app/login" />
</Router>
</Layout>
)
export default App
如何为这些路由实现代码拆分?假设Details
是非常昂贵的组件。现在,无论是否会被很少访问,它都将被捆绑和加载。
我们可以解决这个问题吗?
答案 0 :(得分:1)
您可以使用React.lazy:
如果Details
非常昂贵。代替
import Details from "../components/Details"
做
const Details = lazy(() => import("../components/Details"))
注意:您还需要使用Suspense
添加后备组件:
<Suspense fallback={<div>Loading...</div>}>
<Router>
<PrivateRoute path="/app/profile" component={Home} />
<PrivateRoute path="/app/details" component={Details} />
<Login path="/app/login" />
</Router>
</Suspense>
查看React的官方文档:https://reactjs.org/docs/code-splitting.html#reactlazy
答案 1 :(得分:0)
您应该阅读他们的博客文章中的this segment。这里是重要的部分:
gatsby-link和链接rel =“ prefetch”
由gatsby导出的Link组件附带一个 IntersectionObserver。行为是双重的:
An IntersectionObserver is registered for all links This will register an idle prefetch for a request for that link’s resources See the code for gatsby-link On hover a fetch will be used to send a non-idle request for that link’s resources This will use an onMouseEnter prop to make the resources available via our internal loader See the code for gatsby-link
解决方案非常简单:
使用经典的HTML a标签而不是Gatsby Link。
如Gatsby项目维护者在issuee中所讨论的那样,通过这种方式禁用了预取。