const about = (location, cb) => { require.ensure([], require => { cb(null, require('../Component/about').default) },'about') } //配置route <Route path="helpCenter" getComponent={about} />
import React from 'react'; import PropTypes from 'prop-types'; class Bundle extends React.Component { state = { // short for "module" but that's a keyword in js, so "mod" mod: null } componentWillMount() { // 加載初始狀態 this.load(this.props); } componentWillReceiveProps(nextProps) { if (nextProps.load !== this.props.load) { this.load(nextProps); } } load(props) { // 重置狀態 this.setState({ mod: null }); // 傳入組件的組件 props.load((mod) => { this.setState({ // handle both es imports and cjs mod: mod.default ? mod.default : mod }); }); } render() { // if state mode not undefined,The container will render children return this.state.mod ? this.props.children(this.state.mod) : null; } } Bundle.propTypes = { load: PropTypes.func, children: PropTypes.func }; export default Bundle;
import aContainer from 'bundle-loader?lazy!./containers/A' const A = (props) => ( <Bundle load={aContainer}> //這裏只是給this.props.child傳一個方法,最後在Bundle的render裏面調用 {(Container) => <Container {...props}/>} </Bundle> )
render() { return ( <div> <h1>Welcome!</h1> <Route path="/about" component={About}/> <Route path="/dashboard" component={A}/> </div> ) }
先看這段代碼:php
module.exports = function (cb) { __webpack_require__.e/* require.ensure */(2).then((function (require) { cb(__webpack_require__(305)); }).bind(null, __webpack_require__)).catch(__webpack_require__.oe); };
這裏是咱們經過import loadDashboard from 'bundle-loader?lazy!./containers/A'
這種方式引入的container控件。咱們使用了bundle-loader將A的源碼轉化成了上面的代碼,具體實現你們能夠看bundle-loader源碼,代碼不多。react
上面說到Bundle.js其實就使用來處理這個文件的,這個文件須要一個callback的參數,在Bundle的load方法中,咱們會設置這個callback,當路由要調到A Container這裏的時候,就回去加載A Container,而後調用這個callback,這個callback會調用setState方法,將咱們以前傳入的load設置給mod,而後渲染出來。webpack
這裏匹配的是src/routers/下面的containers文件夾下面全部的js文件,包括二級目錄。git
{ // 匹配routers下面全部文件 // ([^/]+)\/?([^/]*) 匹配xxx/xxx 或者 xxx test: /containers\/([^/]+)\/?([^/]*)\.jsx?$/, include: path.resolve(__dirname, 'src/routers/'), // loader: 'bundle-loader?lazy' loaders: ['bundle-loader?lazy', 'babel-loader'] }
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ var loaderUtils = require("loader-utils"); module.exports = function() {}; module.exports.pitch = function(remainingRequest) { this.cacheable && this.cacheable(); var query = loaderUtils.getOptions(this) || {}; if(query.name) { var options = { context: query.context || this.options.context, regExp: query.regExp }; var chunkName = loaderUtils.interpolateName(this, query.name, options); var chunkNameParam = ", " + JSON.stringify(chunkName); } else { var chunkNameParam = ''; } var result; if(query.lazy) { result = [ "module.exports = function(cb) {\n", " require.ensure([], function(require) {\n", " cb(require(", loaderUtils.stringifyRequest(this, "!!" + remainingRequest), "));\n", " }" + chunkNameParam + ");\n", "}"]; } else { result = [ "var cbs = [], \n", " data;\n", "module.exports = function(cb) {\n", " if(cbs) cbs.push(cb);\n", " else cb(data);\n", "}\n", "require.ensure([], function(require) {\n", " data = require(", loaderUtils.stringifyRequest(this, "!!" + remainingRequest), ");\n", " var callbacks = cbs;\n", " cbs = null;\n", " for(var i = 0, l = callbacks.length; i < l; i++) {\n", " callbacks[i](data);\n", " }\n", "}" + chunkNameParam + ");"]; } return result.join(""); } /* Output format: var cbs = [], data; module.exports = function(cb) { if(cbs) cbs.push(cb); else cb(data); } require.ensure([], function(require) { data = require("xxx"); var callbacks = cbs; cbs = null; for(var i = 0, l = callbacks.length; i < l; i++) { callbacks[i](data); } }); */
import React from 'react'; import PropTypes from 'prop-types'; import * as reactRedux from 'react-redux'; import BaseContainer from '../../../containers/ReactBaseContainer'; class A extends BaseContainer { constructor(props) { super(props); this.renderCustom = function renderCustom() { return ( <div > Hello world In A </div> ); }; } render() { // 返回父級view return super.render(); } } A.propTypes = { dispatch: PropTypes.func, }; function mapStateToProps(state) { return { state }; } export default reactRedux.connect(mapStateToProps)(A);
import React from 'react'; import { BrowserRouter, Switch, Link } from 'react-router-dom'; import { Route } from 'react-router'; import PostContainer from '../containers/PostsContainer'; // 設置trunk文件的名字 the basename of the resource import aContainer from './containers/A'; import bContainer from './containers/B'; import cContainer from './containers/C'; import Bundle from '../utils/Bundle'; const A = () => ( <Bundle load={aContainer}> {Component => <Component />} </Bundle> ) const app = () => <div> {/* path = "/about" */} {/* "/about/" 能夠,但"/about/1"就不能夠了 exact 配置以後,須要路徑絕對匹配,多個斜槓沒有關係,這裏直接在瀏覽器裏面設置還有問題*/} {/* path = "/about/" */} {/* "/about/1" 能夠,但"/about"就不能夠了 用了strict,path要大於等於的關係,少一個斜槓都不行 */} {/* exact 和 strick 都用了就必須如出一轍,連斜槓都同樣 */} <Link to="/about/"> Link to about</Link> <Route path="/" component={PostContainer} /> <Route path="/about/" component={A} /> {/* <Route path="/home" component={B} /> <Route component={C} /> */} </div> ; export default function () { // 用來判斷本地瀏覽器是否支持刷新 const supportsHistory = 'pushState' in window.history; return ( <BrowserRouter forceRefresh={!supportsHistory} keyLength={12}> <div> {app()} </div> </BrowserRouter> ); }
import React, { Component } from "react"; export default function asyncComponent(importComponent) { class AsyncComponent extends Component { constructor(props) { super(props); this.state = { component: null }; } async componentDidMount() { const { default: component } = await importComponent(); this.setState({ component: component }); } render() { const C = this.state.component; return C ? <C {...this.props} /> : null; } } return AsyncComponent; }
const Buttons = asyncComponent(() => import("./button"));
"presets": [ [ "es2015" ], "stage-1", // 應用了es7的語法,因此必須有這個配置 "react" ],