react koa rematch 如何打造一套服務端渲染架子

這篇文章主要介紹了react koa rematch 如何打造一套服務端渲染架子,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨着小編來一起學習學習吧

前言

本次講述的內容主要是 react 與 koa 搭建的一套 ssr 框架,是在別人造的輪子上再添加了一些自己的想法和完善一下自己的功能。

本次用到的技術爲: react | rematch | react-router | koa

react服務端渲染優勢

SPA(single page application)單頁應用雖然在交互體驗上比傳統多頁更友好,但它也有一個天生的缺陷,就是對搜索引擎不友好,不利於爬蟲爬取數據(雖然聽說chrome能夠異步抓取spa頁面數據了);

SSR與傳統 SPA(Single-Page Application - 單頁應用程序)相比,服務器端渲染(SSR)的優勢主要在於:更好的 SEO 和首屏加載效果。

在 SPA 初始化的時候內容是一個空的 div,必須等待 js 下載完纔開始渲染頁面,但 SSR 就可以做到直接渲染html結構,極大地優化了首屏加載時間,但上帝是公平的,這種做法也增加了我們極大的開發成本,所以大家必須綜合首屏時間對應用程序的重要程度來進行開發,或許還好更好地代替品(骨架屏)。

react服務端渲染流程

組件渲染

首先肯定是根組件的render,而這一部分和SPA有一些小不同。

使用 ReactDOM.render() 來混合服務端渲染的容器已經被棄用,並且會在React 17 中刪除。使用hydrate() 來代替。

hydrate與 render 相同,但用於混合容器,該容器的HTML內容是由 ReactDOMServer 渲染的。 React 將嘗試將事件監聽器附加到現有的標記。

hydrate 描述的是 ReactDOM 複用 ReactDOMServer 服務端渲染的內容時儘可能保留結構,並補充事件綁定等 Client 特有內容的過程。

import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.hydrate(<App />, document.getElementById('app'));

在服務端中,我們可以通過 renderToString 來獲取渲染的內容來替換 html 模版中的東西。

const jsx = 
  <StaticRouter location={url} context={routerContext}>
    <AppRoutes context={defaultContext} initialData={data} />
  </StaticRouter>
  
const html = ReactDOMServer.renderToString(jsx);

let ret = `
  <!DOCTYPE html>
    <html lang="en">
    <head>
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no, user-scalable=no">
    </head>
    <body>
     <div id="app">${html}</div>
    </body>
  </html>
`;

return ret;

服務端返回替換後的 html 就完成了本次組件服務端渲染。

路由同步渲染

在項目中避免不了使用路由,而在SSR中,我們必須做到路由同步渲染。

首先我們可以把路由拆分成一個組件,服務端入口和客戶端都可以分別引用。

function AppRoutes({ context, initialData }: any) {
 return (
  <Switch>
   {
    routes.map((d: any) => (
     <Route<InitRoute>
      key={d.path}
      exact={d.exact}
      path={d.path}
      init={d.init || ''}
      component={d.component}
     />
    ))
   }
   <Route path='/' component={Home} />
  </Switch>
 );
}

(routes.js)

export const routes = [
 {
  path: '/Home',
  component: Home,
  init: Home.init,
  exact: true,
 },
 {
  path: '/Hello',
  component: Hello,
  init: Hello.init,
  exact: true,
 }
];

這樣我們的路由基本定義完了,然後客戶端引用還是老規矩,和SPA沒什麼區別

import { BrowserRouter as Router } from 'react-router-dom';
import AppRoutes from './AppRoutes';
class App extends Component<any, Readonly<State>> {
...
 render() {
  return (
  <Router>
   <AppRoutes/>
  </Router>
  );
 }
}

在服務端中,需要使用將BrowserRouter 替換爲 StaticRouter 區別在於,BrowserRouter 會通過HTML5 提供的 history API來保持頁面與URL的同步,而StaticRouter 則不會改變URL,當一個 匹配時,它將把 context 對象傳遞給呈現爲 staticContext 的組件。

const jsx = 
  <StaticRouter location={url}>
    <AppRoutes />
  </StaticRouter>
  
const html = ReactDOMServer.renderToString(jsx);

至此,路由的同步已經完成了。

redux同構

在寫這個之前必須先了解什麼是注水和脫水,所謂脫水,就是服務器在構建 HTML 之前處理一些預請求,並且把數據注入html中返回給瀏覽器。而注水就是瀏覽器把這些數據當初始數據來初始化組件,以完成服務端與瀏覽器端數據的統一。

組件配置

在組件內部定義一個靜態方法

class Home extends React.Component {
...
 public static init(store:any) {
  return store.dispatch.Home.incrementAsync(5);
 }
 componentDidMount() {
  const { incrementAsync }:any = this.props;
  incrementAsync(5);
 }
 render() {
 ...
 }
}

const mapStateToProps = (state:any) => {
 return {
  count: state.Home.count
 };
};

const mapDispatchToProps = (dispatch:any) => ({
 incrementAsync: dispatch.Home.incrementAsync
});
export default connect(
 mapStateToProps,
 mapDispatchToProps
)(Home);

由於我這邊使用的是rematch,所以我們的方法都寫在model中。

const Home: ModelConfig= {
 state: {
  count: 1
 }, 
 reducers: {
  increment(state, payload) {
   return {
    count: payload
   };
  }
 },
 effects: {
  async incrementAsync(payload, rootState) {
   await new Promise((resolve) => setTimeout(resolve, 1000));
   this.increment(payload);
  }
 }
};
export default Home;

然後通過根 store 中進行 init。

import { init } from '@rematch/core';
import models from './models';

const store = init({
 models: {...models}
});

export default store;

然後可以綁定在我們 redux 的 Provider 中。

<Provider store = {store}>
  <Router>
   <AppRoutes
    context={context}
    initialData={this.initialData}
   />
  </Router>
</Provider>

路由方面我們需要把組件的 init 方法綁定在路由上方便服務端請求數據時使用。

<Switch>
   {
    routes.map((d: any) => (
     <Route<InitRoute>
      key={d.path}
      exact={d.exact}
      path={d.path}
      init={d.init || ''}
      component={d.component}
     />
    ))
   }
   <Route path='/' component={Home} />
  </Switch>

以上就是客戶端需要進行的操作了,因爲 SSR 中我們服務端也需要進行數據的操作,所以爲了解耦,我們就新建另一個 ServiceStore 來提供服務端使用。

在服務端構建 Html 前,我們必須先執行完當前組件的 init 方法。

import { matchRoutes } from 'react-router-config';
// 用matchRoutes方法獲取匹配到的路由對應的組件數組
const matchedRoutes = matchRoutes(routes, url);
const promises = [];
for (const item of matchedRoutes) {
 if (item.route.init) {
  const promise = new Promise((resolve, reject) => {
   item.route.init(serverStore).then(resolve).catch(resolve);
  });
  promises.push(promise);
 }
}
return Promise.all(promises);

注意我們新建一個 Promise 的數組來放置 init 方法,因爲一個頁面可能是由多個組件組成的,我們必須等待所有的 init 執行完畢後才執行相應的 html 構建。

現在可以得到的數據掛在 window 下,等待客戶端的讀取了。

let ret = `
   <!DOCTYPE html>
    <html lang="en">
    <head>
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no, user-scalable=no">
    </head>
    <body>
     <div id="app">${html}</div>
     <script type="text/javascript">window.__INITIAL_STORE__ = ${JSON.stringify(
      extra.initialStore || {}
     )}</script>
    </body>
   </html>
  `;

然後在我們的客戶端中讀取剛剛的 initialStore 數據

....
const defaultStore = window.__INITIAL_STORE__ || {};
const store = init({
 models,
 redux: {
  initialState: defaultStore
 }
});

export default store;

至此,redux的同構基本完成了,因爲邊幅的限定,我就沒有貼太多代碼,大家可以到文章底部的點擊我的倉庫看看具體代碼哈,然後我再說說幾個 redux 同構中比較坑的地方。

1.使用不了 @loadable/component 異步組件加載,因爲不能獲取組件內部方法。 解決的辦法就是在預請求我們不放在組件中,直接拆分出來寫在一個文件中統一管理,但我嫌這樣不好管理就放棄了異步加載組件了。

2.在客戶端渲染的時候如果數據一閃而過,那就是初始化數據並沒有成功,當時這裏卡了我好久喔。

css樣式直出

首先,服務端渲染的時候,解析 css 文件,不能使用 style-loader 了,要使用 isomorphic-style-loader 。使用 style-loader 的時候會有一閃而過的現象,是因爲瀏覽器是需要加載完 css 才能把樣式加上。爲了解決這樣的問題,我們可以通過isomorphic-style-loader 在組件加載的時候把 css 放置在全局的 context 裏面,然後在服務端渲染時候提取出來,插入到返回的HTML中的 style 標籤。

組件的改造

import withStyles from 'isomorphic-style-loader/withStyles';

@withStyles(style)
class Home extends React.Component {
...
 render() {
  const {count}:any = this.props;
  return (
  ...
  );
 }
}
const mapStateToProps = (state:any) => {
 return {
  count: state.Home.count
 };
};

const mapDispatchToProps = (dispatch:any) => ({
 incrementAsync: dispatch.Home.incrementAsync
});
export default connect(
 mapStateToProps,
 mapDispatchToProps
)(Home);

withStyle 是一個柯里化函數,返回的是一個新的組件,並不影響 connect 函數,當然你也可以像 connect 一樣的寫法。withStyle 主要是爲了把 style 插入到全局的 context 裏面。

根組件的修改

import StyleContext from 'isomorphic-style-loader/StyleContext';

const insertCss = (...styles:any) => {
 const removeCss = styles.map((style:any) => style._insertCss());
 return () => removeCss.forEach((dispose:any) => dispose());
};

ReactDOM.hydrate(
  <StyleContext.Provider value={{ insertCss }}>
    <AppError>
     <Component />
    </AppError>
  </StyleContext.Provider>,
  elRoot
);

這一部分主要是引入了 StyleContext 初始化根部的context,並且定義好一個 insertCss 方法,在組件 withStyle 中觸發。

部分 isomorphic-style-loader 源碼

...
function WithStyles(props, context) {
  var _this;
  _this = _React$PureComponent.call(this, props, context) || this;
  _this.removeCss = context.insertCss.apply(context, styles);
  return _this;
 }

 var _proto = WithStyles.prototype;

 _proto.componentWillUnmount = function componentWillUnmount() {
  if (this.removeCss) {
   setTimeout(this.removeCss, 0);
  }
 };

 _proto.render = function render() {
  return React.createElement(ComposedComponent, this.props);
 };
 ...

可以看到 context 中的 insert 方法就是根組件中的 定義好的 insert 方法,並且在 componentWillUnmount 這個銷燬的生命週期中把之前 style 清除掉。而 insert 方法主要是爲了給當前的 style 定義好id並且嵌入,這裏就不展開說明了,有興趣的可以看一下源碼。

服務端中獲取定義好的css

const css = new Set(); // CSS for all rendered React components

const insertCss = (...styles :any) => {
 return styles.forEach((style:any) => css.add(style._getCss()));
};

const extractor = new ChunkExtractor({ statsFile: this.statsFile });

const jsx = extractor.collectChunks(
 <StyleContext.Provider value={{ insertCss }}>
  <Provider store={serverStore}>
    <StaticRouter location={url} context={routerContext}>
     <AppRoutes context={defaultContext} initialData={data} />
    </StaticRouter>
  </Provider>
 </StyleContext.Provider>
);

const html = ReactDOMServer.renderToString(jsx);
const cssString = Array.from(css).join('');
...

其中 cssString 就是我們最後獲取到的 css 內容,我們可以像 html 替換一樣把 css 嵌入到 html 中。

let ret = `
   <!DOCTYPE html>
    <html lang="en">
    <head>
     ...
     <style>${extra.cssString}</style>
    </head>
    <body>
     <div id="app">${html}</div>
     ...
    </body>
   </html>
  `;

那這樣就大功告成啦!!!!

我來說一下在做這個的時候遇到的坑

1.不能使用分離 css 的插件 mini-css-extract-plugin ,因爲分離 css 和把 css 放置到 style 中會有衝突,引入github大神的一句話

With isomorphic-style-loader the idea was to always include css into js files but render into dom only critical css and also make this solution universal (works the same on client and server side). If you want to extract css into separate files you probably need to find another way how to generate critical css rather than use isomorphic-style-loader.

2.很多文章說到在 service 端的打包中不需要打包 css,那是因爲他們使用的是style-loader 的情況,我們如果使用 isomorphic-style-loader, 我們也需要把 css 打包一下,因爲我們在服務端中畢竟要觸發 withStyle。

總結

因爲代碼太多了,所以只是展示了整個 SSR 流程的思想,詳細代碼可以查看。還有希望大牛們指導一下我的錯誤,萬分感謝!!

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章