没想到服务器 HTML 在 <main> 中包含一个 <div>

Ale*_*ada 4 javascript reactjs server-side-rendering react-router-dom loadable-component

我在一个使用以下项目的项目中工作:

  • 反应/反应-dom@16.9.0
  • @loadable/组件
  • 样式组件
  • 反应路由器dom

该应用程序呈现服务器端和客户端。

我正在使用@loadable/component这种方式动态代码拆分。

路由器.tsx

import * as React from 'react'
import loadable from '@loadable/component'
import { Route, Switch } from 'react-router-dom'

const NotFound = loadable(() =>
  import('../components/NotFound/NotFound' /* webpackChunkName: "notfound" */)
)

const routes = (
  <Switch>
    <Route component={NotFound} />
  </Switch>
)

export default routes
Run Code Online (Sandbox Code Playgroud)

加载页面时,此错误出现在控制台上,页面似乎闪烁了一秒钟。

react-dom.development.js:546 Warning: Did not expect server HTML to contain a <div> in <main>.
Run Code Online (Sandbox Code Playgroud)

当我检查双方(服务器/客户端)的输出时,它们是相同的

当我@loadable/component像下面那样删除时,它可以工作并且错误消失了。

路由器无负载.tsx

import * as React from 'react'
import { Route, Switch } from 'react-router-dom'
import NotFound from '../components/NotFound/NotFound'

const routes = (
  <Switch>
    <Route component={NotFound} />
  </Switch>
)

export default routes
Run Code Online (Sandbox Code Playgroud)

似乎与此有关,@loadable/component但我不是 100% 确定。

Ale*_*ada 5

终于有了这个答案:

  1. 为了@loadable/component正常工作,您需要以/* webpackChunkName: "notfound" */这种方式将神奇的 webpack 注释 ( ) 放在文件路径之前。
const NotFound = loadable(() =>
  import(/* webpackChunkName: "notfound" */ '../components/NotFound/NotFound')
)
Run Code Online (Sandbox Code Playgroud)

参考:

https://github.com/smooth-code/loadable-components/issues/23

  1. 更重要的是,在服务器端,您需要将应用程序包装在 a 中ChunkExtractorManager并传递客户端提取器(我传递的是服务器提取器,文档中不是很清楚)。
const statsFile = path.resolve('./wwwroot/dist/loadable-stats.json')
const extractor = new ChunkExtractor({ 
  statsFile, 
  entrypoints: ['client'] // name of the proper webpack endpoint (default: main)
})

<ChunkExtractorManager extractor={extractor}>
  <App />
</ChunkExtractorManager>
Run Code Online (Sandbox Code Playgroud)

这是一个关于如何实现它的适当清晰的例子:

https://github.com/iamssen/seed

2019 年 9 月 24 日更新

添加到官方文档

https://www.smooth-code.com/open-source/loadable-components/docs/server-side-rendering/#chunkextractor-entrypoints