reactjs code splitting,webpack2 loader
npm install react-dynamic-router-loader
shell
npm i --save-dev react-dynamic-router-loader
`
$3
`javascript
// webpack.config-client.js
...
loader: "react-dynamic-router-loader",
options: {
// Loading Component
asyncDefaultComponent: './components/loading.jsx'
}
...
`
`javascript
// ./components/loading.jsx
import React from 'react';
const _AsyncComponent = (
loaderComponent,
loadingComponent,
cacheComponent
) => (
class _AsyncComponent extends React.Component {
state = {
Component: null
}
async componentWillMount() {
let Component = cacheComponent || await loaderComponent();
this.setState({
Component
});
}
render() {
const { Component } = this.state;
return (Component) ?
:
loadingComponent();
}
}
);
// Currently only to do so
module.exports = _AsyncComponent;
`
`javascript
// Reactjs Code
...
/ webpackChunkName: "index" /
/ loadingComponentPath: "./loading.jsx" /
'path/my-component.jsx')} />
...
// webpackChunkName
// the "import" feature of the CommonJS API for webpack2
/*
loadingComponentPath is the loader's property
that specifies the corresponding loadingComponent
for this component by configuring
this property or the default asyncDefaultComponent
ps: Path is relativePath, equal "require('[path]') "
*/
// Reactjs Code 2
class MyComponent extends React.Component {
preRender(){
// Don't use props.
// because this.props not equal MyComponent's props
return (
My Loading View
);
}
}
`
$3
`javascript
// webpack config must has client and server config
let clientConfig = {
...
// client config
...
};
let serverConfig = {
...
// server config
...
};
module.exports = [serverConfig, clientConfig]
`
$3
The following instructions assume you need server-side rendering
Based on server-side rendering, js needs to write
`html
`
directly in html at initialization. And ReactDOM.render function needs to go through
`javascript
setTimeout (function () {
RenderDOM.render (xxxx)
});
``