Separating CSS code with Webpack 2 and React Router

I am code breaking my JavaScript files using React Router and Webpack 2 as follows:

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 */ } }; 

What are the results on this bunch:

 public/ vendor.bundle.js bundle.js 0.bundle.js 1.bundle.js 2.bundle.js 

This means that the end user receives only the JavaScript that he needs, in accordance with the route in which he is.

The thing is, for the css part, I do not find any resource to do the same thing that I need to break CSS in accordance with the needs of the user.

Is there a way to do this with Webpack 2 and React Router?

+7
reactjs webpack webpack-2 css-modules
source share
2 answers

Yes, it can be done. You will 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 the full example here:

https://github.com/webpack/webpack/tree/master/examples/multiple-entry-points-commons-chunk-css-bundle

+2
source share

Although I can not answer your question about how to split css files so that only the files you need are downloaded , how you want the question to be answered (there is no plug-in or this type), I hope to give you a possible alternative.

styled-components use the new ES6 tagged template literal function to create elements inside a javascript file. I think that using this library will solve your problem of downloading only the necessary css files, because there will be no more css per se files.

react-boilerplate chose styled-components over sass because

styled-components have a more powerful approach: instead of trying to give a language programmatic way of modeling, it draws logic and configuration in JS. These features belong.

Thus, the use of styled-components will not only solve your problem of downloading only the necessary css, but also add to the decoupling of your application, simplify the verification of the design and causes of your application.

Here's a live demo where you can experiment with styled-components and see how it works.

+2
source share

All Articles