官方给react-loadable的定义是:
A higher order component for loading components with dynamic imports.
动态路由示例
withLoadable.js
import React from 'react'
import Loadable from 'react-loadable';
export function withLoadable (comp) {
return Loadable({
loader: comp,
loading: () => (
<div>Loading...</div>
)
})
}
Root.js
import React from 'react'
import { Provider } from 'react-redux'
import { Route, Switch } from 'react-router-dom'
import { ConnectedRouter } from 'react-router-redux'
import createHistory from 'history/createHashHistory'
import App from './App'
import { withLoadable } from '../components/withLoadable'
const history = createHistory()
const Home = withLoadable(() => import('./Home/Home'))
const Root = ({ store }) => (
<Provider store={store}>
<App>
<ConnectedRouter history={history}>
<Switch>
<Route path="*" component={Home}/>
</Switch>
</ConnectedRouter>
</App>
</Provider>
)
1 style: security content policy报错
当less文件打开sourcemap后,遇到security content policy 报错,屏蔽就好了,现在也没弄明白原因,如遇大神,请指教!
{
test: /\.less$/,
loader: ExtractTextPlugin.extract(
Object.assign(
{
fallback: {
loader: require.resolve('style-loader'),
options: {
hmr: false
}
},
use: [
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
minimize: true
/* 否则security centent policy error */
// sourceMap: shouldUseSourceMap
}
},
{
loader: require.resolve('postcss-loader'),
options: {
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
autoprefixer({
flexbox: true
})
]
}
},
{
loader: 'less-loader',
options: { modifyVars: theme }
}
]
},
extractTextPluginOptions
)
)
}
2 createBrowserHistory或者createHashHistory对于react-loadable加载模块路径的影响
当使用createBrowserHistory时,路由跳转会根据当前路径加载模块,假设当前路径为:'localhost:3000/',当跳转到finished时,会加载/finished/static/js/finished_module.js, 从而报错,但应该加载/static/js/finished_module.js,所以,最后使用hash路径
<Provider store={store}>
<App>
<ConnectedRouter history={history}>
<Switch>
<Route path="/additionalFunc/:cardName"
component={AdditionalFunc}/>
<Route path="/finished" component={Finished}/>
{/*<Route path="/wisdomWash" component={WisdomWash}/>*/}
{/*<Route path="/geek" component={Geek}/>*/}
<Route path="*" component={Home}/>
</Switch>
</ConnectedRouter>
</App>
</Provider>
参考资料:https://github.com/jamiebuilds/react-loadable