基本上,它归结为预先创建你将需要的所有块。那么你只需要一种方式来动态引用它们。这里的解决方案,我根据我的上:
http://henleyedition.com/implicit-code-splitting-with-react-router-and-webpack
这里是我做的,因为我不使用阵营路由器(边注:我不觉得这是对终极版或动画的良好匹配):
//loader:
{
test: (folder)\/.*\.js,
include: path.resolve(__dirname, 'src')
loader: ['lazy?bundle', 'babel']
}
//dynamic usage within React component:
const My_COMPONENTS = {
ComponentA: require('./folder/ComponentA'),
ComponentB: require('./folder/ComponentB'),
}
class ParentComponent extends React.Component {
componentDidMount() {
My_COMPONENTS[this.props.name](component => this.setState({component}));
}
render() {
return <this.state.component />;
}
}
所以结果是要动态渲染的成分,但是从静态组预定的可能性 - 所有一会儿,才不发送更多的客户比大块访问者实际感兴趣
另外,这里是一个组件我做这个好:
import React from 'react';
import Modal from './widgets/Modal';
export default class AjaxModal extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
Content: null
};
}
componentDidMount() {
if(this.props.show) {
this.loadContent();
}
}
componentWillReceiveProps({show}) {
if(show && !this.state.Content) {
this.loadContent(1200); //dont interfere with animation
}
}
loadContent(ms=0) {
setTimeout(() => {
this.props.requestLazyBundle(({default: Content}) => {
this.setState({Content});
});
}, ms);
}
render() {
let {Content} = this.state;
return (
<Modal title={this.props.title} {...this.props} loading={!Content}>
{Content ? <Content /> : null}
</Modal>
);
}
}
通通过异步需要捆绑功能this.props.requestLazybundle
,就像这样:
render() {
let requestLazyBundle = require('bundle?lazy&name=AnotherComponent!../content/AnotherComponent');
return (
<AjaxModal title='Component Name' {...props} requestLazyBundle={requestLazyBundle} />
);
}
'require.ensure'静态分析,正确。你会找到另一种方式。 –
是否有可能使用webpack? – madCode
你可以设置一个[require.context](https://webpack.github.io/docs/context.html)然后'require'。 –