App/index.js
import React from 'react';
import { with_code_splitting } from 'components/App/Code_splitting/HOC';
export default class App extends React.PureComponent {
render () {
return <Child/>;
}
}
const Child = with_code_splitting({ dynamic:() => import('components/App/Child'), static:() => require.resolveWeak('components/App/Child') });App/Code_splitting/HOC.js
import React from 'react';
export function with_code_splitting (options) {
return class Decorated_component extends React.Component {
static component = null;
state = { component:Decorated_component.component };
componentWillMount() {
if (!this.state.component) {
if (process.env.NODE_ENV !== 'server_side_rendering') {
options.dynamic()
.then(({ default:component }) => {
Decorated_component.component = component;
this.setState({ component });
});
}
else { // for server-side-rendering
const module_ID = options.static();
console.log(__webpack_modules__[module_ID]); // undefined
this.setState({ component:__webpack_require__(module_ID) });
}
}
}
render() {
if (this.state.component) return <this.state.component {...this.props} />
else return null;
}
}
}我使用的是webpack 3.9.1,react 16.0.0。
我正在尝试使用SSR实现代码拆分。但“require.resolveWeak”中的“module_ID”不在__webpack_modules__数组中。
只有该索引处的元素为空。
客户机上的代码拆分效果很好。
我不知道我误解了什么。我想要一个答案。感谢您的阅读。
发布于 2018-02-15 16:51:28
您是否解决了在客户端首次渲染时没有在服务器上使用的异步包的问题?
对于其他试图解决这个问题并在这个问题上遇到困难的人。使用代码拆分的最简单方法是使用像react-loadable (https://github.com/jamiebuilds/react-loadable)这样的库
它提供了方便的方法来渲染加载状态,超时,跟踪加载到哪些块的SSR方法,您可以将它们添加到页面,以便在开始渲染之前加载它们。
https://stackoverflow.com/questions/48706441
复制相似问题