注意是 "webpack2"
, 先上代码
//client.js
render(
<Provider store={store}>
<Router history={history} routes={routes} />
</Provider>,
document.getElementById('app')
);
//router.js
const ac = (cb, path) => {
if (typeof require.ensure != 'function'){
cb(null, require(path));
return false;
}
return true;
};
const routes = {
component: Init,
childRoutes: [
{
path: 'login',
getComponents(nextState, cb){
ac(cb, '../containers/login') && (require.ensure([], function (require) {
cb(null, require("../containers/login").default);
}, 'login'));
}
}
]
};
export default routes;
//webpack.config.json
module.exports = {
context: path.join(__dirname, '../'),
entry: {
v1: ['react'],
client: ['./app/client.js']
},
output: {
path: path.resolve(__dirname, '../public/static/js-built'),
publicPath: '/static/js-built/',
filename: '[name].js',
chunkFilename: '[name].js'
},
module: {
rules: [
{
test: /(.jsx|.js)$/,
exclude: [/node_modules/],
use: [
{
loader: 'babel-loader',
options: {
babelrc: false,
presets: ['react', 'es2015', 'stage-0'],
plugins:['transform-decorators-legacy', ["transform-runtime", {
"polyfill": false,
"regenerator": true
}]]
}
}
]
}
]
},
resolve: {
extensions: ['.js', '.jsx']
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
names: ['v1']
}),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin()
]
};
//Login组件
export default class Login extends Component{
render(){
return (
<div>登录页面</div>
)
}
}
//控制台报错
Warning: React attempted to reuse markup in a container but the checksum was invalid. This generally means that you are using server rendering and the markup generated on the server was not what the client was expecting. React injected new markup to compensate which works but you have lost many of the benefits of server rendering. Instead, figure out why the markup being generated is different on the client or server:
(client) <!-- react-empty: 1 -
(server) <div class="container
控制台显示client
没有获取到任何东西,所以和服务端的渲染冲突了.但是页面是可以运行的.
假如不用react-router
,client
就能够获取到,如下:
render(
<div>123</div>,
document.getElementById('app')
);
//控制台
Warning: React attempted to reuse markup in a container but the checksum was invalid. This generally means that you are using server rendering and the markup generated on the server was not what the client was expecting. React injected new markup to compensate which works but you have lost many of the benefits of server rendering. Instead, figure out why the markup being generated is different on the client or server:
(client) "" data-reactid="1">123</div>
(server) "" data-reactid="1">登录页面</div>
但是require.ensure
貌似并没有错?
最后附上版本
"react": "^15.3.2"
"webpack": "^2.3.3"
"react-router": "^3.0.5"