0

I'm using react-router 2.4.0 with React 15.2.1 and Webpack. I see that styles are being loaded via IndexRoute component (Main, in this example) although it's not being loaded.

Consider the following sources:

AppRouter.js

<Router history={history}>
    <Route path='/' component={App}>
        <IndexRoute component={Main} onEnter={requireLogin} />
        <Route path='login' component={LoginPage} />
    </Route>
</Router>

function requireLogin(nextState, replace) {
    if (!getIsUserLoggedIn()) {
        replace('/login');
    }
}

Main.js

...

import '../styles/Main.scss';

...

webpack.config.js:

...

module: {
    loaders: [
        {
            test: /\.scss$/,
            loader: 'style!css!sass!postcss-loader'
        }
    ]
},
postcss: [autoprefixer({ browsers: ['last 2 versions'] })]

When navigating to / and the user is logged out, the router do redirect to /login, but all styles that are loaded in Main.scss are being appended to the DOM.

How can I prevent that from happen, and load only LoginPage component styles?

tomericco
  • 1,544
  • 3
  • 19
  • 30
  • Google for "react router webpack code splitting". This question is too broad for SO. – Yury Tarabanko Jul 25 '16 at 10:10
  • IMHO code splitting is an overkill to achieve the desired behavior. Why react router loads the component which is not intended to be rendered? Maybe there is a hack without using IndexRoute? – tomericco Jul 25 '16 at 10:23
  • Well, react router loads nothing. It is webpack and it's plugins (style and css) that create and load css file. BTW check `style-loader` [docs](https://github.com/webpack/style-loader#reference-counted-api) `use/unuse` might help/ – Yury Tarabanko Jul 25 '16 at 10:32
  • Thanks Yury, I think that the solution is to split the code as you suggested. – tomericco Jul 25 '16 at 11:16

0 Answers0