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

Did not expect server HTML to contain a <div> in <main>

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

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

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

router.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

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

react-dom.development.js:546 Warning: Did not expect server HTML to contain a <div> in <main>.

当我检查两侧的输出时 (server/client),它们 相同

当我像下面那样删除 @loadable/component 时,它起作用了,错误消失了。

无路由器loadable.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

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

我认为问题是您的 NotFound 组件未加载,因此 Route 不知道要渲染什么导致错误。

您需要修改如下内容:

<Route path="/404/" exact component={props => <NotFound {...props} />} />

终于有答案了:

  1. 为了@loadable/component正常工作,你需要在文件路径前添加神奇的webpack注释(/* webpackChunkName: "notfound" */)。
const NotFound = loadable(() =>
  import(/* webpackChunkName: "notfound" */ '../components/NotFound/NotFound')
)

参考:

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

  1. 更重要的是,在服务器端,您需要将应用程序包装在 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>

这里有一个关于如何实现它的正确清晰的例子:

https://github.com/iamssen/seed

2019 年 9 月 24 日更新

添加到官方文档

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