基本上,它歸結爲預先創建你將需要的所有塊。那麼你只需要一種方式來動態引用它們。這裏的解決方案,我根據我的上:
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'。 –