Aug*_*tos 5 reactjs react-static
我们有一个大型且复杂的传统 React 应用程序,我们在过去几年中一直在构建它。它加载一个index.html,注入javascript并像往常一样从API获取数据。不幸的是,冷加载时间非常糟糕(平均 5 - 7 秒)。一旦所有内容加载完毕,它会像往常一样快速,但冷加载时间会在特定的“关键”页面中杀死我们。这些是我们的公共用户页面,格式为:https://mywebsite/userId
我们正在寻找一种方法来显着加快这些路线的加载时间,其方法超越代码分割或资源优化。我们已经做到了这些,并且正在通过 CDN 提供我们的应用程序。
我们研究了创建这些用户页面的静态“快照”,我们需要使用像react-static这样的东西快速加载,并将它们作为静态版本提供并稍后进行水化。使用 next.js 或 gatsby 之类的东西重写我们的项目不是一个选择,因为它需要太多的工作。SSR 也不是一个选项,因为我们的整个后端都是用 Django 而不是 Node.js 编码的
我们走在正确的轨道上吗?是否可能/值得使用react-static(或类似的工具)来做到这一点?有很多关于如何从头开始创建反应静态项目的文档,但没有关于如何转换现有项目的文档,即使它只是我们需要的一小部分路由。
此外,一旦用户页面上的数据发生变化,我们如何触发适当快照的“重建”?用户更新数据的频率并不高,大约每月 4 次或 3 次,但我们有 3000 名用户,因此平均每小时更新 15 次可能是正常的。我们可以只触发实际更改的路由的重建吗?
小智 1
就像你说的,你可以使用react-static。
他们有一个功能可以完全满足您的需求(用户的特定页面)。
在他们的示例中,他们使用一系列帖子为每个帖子生成特定的静态文件。
加载时间要少得多,因为它只是 html 静态文件。
想象一下这样的场景:
[
{
id: 'foo',
...
},
{
id: 'bar',
...
},
...
]
Run Code Online (Sandbox Code Playgroud)
按照下面的示例,这将生成类似这样的内容(在运行时):
- src
- pages
- blog
- posts
- foo // Specific post page
- bar // Specific post page
Run Code Online (Sandbox Code Playgroud)
看一下例子:
//static.config.js
export default {
// resolves an array of route objects
getRoutes: async () => {
// this is where you can make requests for data that will be needed for all
// routes or multiple routes - values returned can then be reused in route objects below
// ATTENTION: In here, instead of posts you'd fetch your users json data
const { data: posts } = await axios.get(
"https://jsonplaceholder.typicode.com/posts"
);
return [
// route object
{
// React Static looks for files in src/pages (see plugins below) and matches them to path
path: "/blog",
// function that returns data for this specific route
getData: () => ({
posts
}),
// an array of children routes
// in this case we are mapping through the blog posts from the post variable above
// and setting a custom route for each one based off their post id
children: posts.map(post => ({
path: `/post/${post.id}`,
// location of template for child route
template: "src/containers/Post",
// passing the individual post data needed
getData: () => ({
post
})
}))
},
];
},
// basic template default plugins
plugins: [
[
require.resolve("react-static-plugin-source-filesystem"),
{
location: path.resolve("./src/pages")
}
],
require.resolve("react-static-plugin-reach-router"),
require.resolve("react-static-plugin-sitemap")
]
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
382 次 |
| 最近记录: |