我正在使用 React Router 和 Webpack 2 来分割我的 JavaScript 文件,如下所示:
export default {
path: '/',
component: Container,
indexRoute: {
getComponent(location, cb) {
if (isAuthenticated()) {
redirect();
} else {
System.import('../landing-page/LandingPage')
.then(loadRoute(cb))
.catch(errorLoading);
}
},
},
childRoutes: [
{
path: 'login',
getComponent(location, cb) {
System.import('../login/Login')
.then(loadRoute(cb))
.catch(errorLoading);
},
},
{ /* etc */
}
};
此 bundle 的结果:
public/
vendor.bundle.js
bundle.js
0.bundle.js
1.bundle.js
2.bundle.js
这意味着最终用户只能根据他/她所在的路线获得他/她需要的 JavaScript。
问题是:对于 css 部分,我没有找到任何资源来做同样的事情,即根据用户的需求拆分 CSS。
有没有办法使用 Webpack 2 和 React Router 来做到这一点?
最佳答案
是的,这是可以做到的。除了 ExtractTextPlugin
之外,您还需要 CommonsChunkPlugin
。另外,定义多个入口点
entry: {
A: "./a",
B: "./b",
C: "./c",
},
并配置 ExtractTextPlugin
以使用入口点名称作为 CSS 文件名
new ExtractTextPlugin({
filename: "[name].css"
}),
在此处查看完整示例:
关于reactjs - 使用 Webpack 2 和 React Router 进行 CSS 代码分割,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42456917/