javascript - 没想到服务器 HTML 包含一个在
问题描述
我正在一个使用以下项目的项目中工作:
- 反应/react-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
加载页面时,控制台上出现此错误,页面似乎闪烁了一秒钟。
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% 确定。
解决方案
终于有这个答案了:
- 为了
@loadable/component
正常工作,您需要以/* webpackChunkName: "notfound" */
这种方式将魔术 webpack 注释 ( ) 放在文件路径之前。
const NotFound = loadable(() =>
import(/* webpackChunkName: "notfound" */ '../components/NotFound/NotFound')
)
参考:
https://github.com/smooth-code/loadable-components/issues/23
- 更重要的是,在服务器端,您需要将您的应用程序包装在 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
添加到官方文档
推荐阅读
- sql - 在 SQL 中查找一系列行的最新日期
- flutter - 当 cron 中的值更改时,GridView.count() 不更新
- c - C生产者/消费者 - 输出相同的数据并在完成之前卡住
- angular - ng build 找不到来自 Git Bash 的打字稿模块
- node.js - Fetch API 在身份验证期间无法获取,同时出现 CORS 错误
- javascript - 选项按钮不会在 PHP 中自动重新加载页面,我在代码中找不到错误
- javascript - 将 this.props 传递给嵌套函数
- android - 将最大高度应用于 BottomSheetDialogFragment 并应用高度变化过渡
- sql - 判断 A 列中的 ID 是否存在 B 列中的特定条目
- javascript - 如何调用方法 myFunction 以返回(名称)我尝试了很多方法但它不起作用