CSS Code Splitting with Webpack 2 and React Router
I'm code splitting my JavaScript files with React Router and Webpack 2 like this:
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 */
}
};
Which results on this bundle:
public/
vendor.bundle.js
bundle.js
0.bundle.js
1.bundle.js
2.bundle.js
Which means that the final user is getting only the JavaScript that he/she needs, according to the route that he/she is in.
The thing is: for the css part, I'm not finding any resource to do same thing, which is to split the CSS according the user's needs.
Is there a way to do it with Webpack 2 and React Router?
Yes, this can be done. You'll need CommonsChunkPlugin
in addition to ExtractTextPlugin
. Also, define multiple entry points
entry: {
A: "./a",
B: "./b",
C: "./c",
},
and configure ExtractTextPlugin
to use entry point names as CSS file names
new ExtractTextPlugin({
filename: "[name].css"
}),
See a full example here:
https://github.com/webpack/webpack/tree/master/examples/multiple-entry-points-commons-chunk-css-bundle
While I may not answer your question how to split css files so that only the necessary ones are loaded the way you want the question to be answered (no plugin or that sort of thing), I hope to give you a possible alternative.
styled-components
use the new ES6 feature tagged template literal to style the components inside the javascript file. I think using this library would solve your problem of loading only the necessary css files, because there would be no more css files per se.
react-boilerplate
chose styled-components
over sass, because
styled-components
have a more powerful approach: instead of trying to give a styling language programmatic abilities, it pulls logic and configuration out into JS these features belong.
So using styled-components
would not only solve your problem of loading only the necessary css, but it would further add to the decoupling of your application, makes it easier to test the design and reason about your app.
Here's the live demo where you can experiment with the styled-components
and check how it works.
上一篇: Alexa,无法链接你的技能