构建时预渲染 SSG

import Support from ‘../../../src/components/Support’ import Badge from ‘../../../src/components/Badge’

icejs 提供构建时预渲染方案,即在构建时渲染页面组件并生成静态的 HTML 文件,以更好解决以下的业务场景:

  • 静态站点生成
  • 没有后端服务的场景下需要更好的 SEO 和更少的首屏渲染时间

开启预渲染

在工程配置文件 build.json 中开启:

  1. {
  2. "ssr": "static"
  3. }

假如现在有以下的目录结构:

  1. ./src
  2. ├── pages
  3. | ├── Dashboard
  4. | ├── Home
  5. ├── app.ts
  6. └── routes.ts

对应的路由配置如下:

  1. import Home from '@/pages/Home';
  2. import Dashboard from '@/pages/Dashboard';
  3. export default [
  4. {
  5. path: '/',
  6. exact: true,
  7. component: Home,
  8. },
  9. {
  10. path: '/dashboard',
  11. exact: true,
  12. component: Dashboard
  13. }
  14. ];

执行 npm run build,将会得到以下构建产物:

  1. ├── build
  2. | ├── dashboard
  3. | | └── index.html # 预渲染 Dashboard 页面组件得到的 HTML
  4. | ├── index.html # 预渲染 Home 页面组件得到的 HTML
  5. | └── js
  6. | └── index.js
  7. └── server
  8. | ├── index.js
  9. | ├── loadable-stats.json
  10. | └── pages-data.json

通过静态服务启动,预渲染后的 HTML 截图如下:

html

与 SSR 一致,SSG 在构建渲染时会调用 app.getInitialData()Page.getInitialData() 方法,可以参考 SSR 文档在这两个方法里按需获取一些动态数据。

部署

使用静态资源服务器

如果是博客、官网等页面数据较为静态的应用,可以直接使用 Nginx、OSS、GitHub Pages 等进行部署,以 Nginx 部署为例:

  1. location / {
  2. root /www/build;
  3. # 访问 localhost:3000/a 依次查找 /www/build/a、/www/build/a/index.html、/www/build/404.html
  4. try_files $uri $uri/ 404.html;
  5. }

进阶用法

预渲染动态路由

预渲染默认不渲染动态路由里的所有页面,比如下方的 /project/:id 路由:

  1. // src/routes.ts
  2. import Project from '@/pages/Project';
  3. export default [
  4. {
  5. path: '/project/:id',
  6. exact: true,
  7. component: Project,
  8. }
  9. ];

如果需要渲染动态路由中的页面,可以配置页面组件的 getStaticPaths() 属性:

  1. // src/pages/Project/index.tsx
  2. const Project = (props) => {
  3. return <></>;
  4. }
  5. +Project.getStaticPaths = async () => {
  6. + return Promise.resolve(['/project/1', '/project/100', '/project/1001']);
  7. +}
  8. export default Project;

执行 npm run build 后,将会得到以下的构建产物:

  1. build
  2. ├── project
  3. | ├── 1
  4. | | └── index.html
  5. | ├── 100
  6. | | └── index.html
  7. | └── 1001
  8. | └── index.html
  9. ├── js
  10. | └── index.js
  11. └── server
  12. | ├── index.js
  13. | ├── loadable-stats.json
  14. | └── pages-data.json