首页 > 解决方案 > 没想到服务器 HTML 包含一个

问题描述

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

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

我正在使用@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

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

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

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

当我像下面这样删除时@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% 确定。

标签: javascriptreactjsreact-router-domserver-side-renderingloadable-component

解决方案


终于有这个答案了:

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

参考:

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>

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

https://github.com/iamssen/seed

更新 24.09.2019

添加到官方文档

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


推荐阅读