M
M
mikor2017-08-01 18:52:01
JavaScript
mikor, 2017-08-01 18:52:01

Dynamic loading of js, css in REACT?

We have React, Webpack, React-Router

Well, one entry point
import React from 'react'
import ReactDOM from 'react-dom'
import { Router, Route, Switch } from 'react-router'
import createHistory from 'history/createBrowserHistory'

// SHARED
import './shared/stylesheets/base.scss'

// APPS
import Welcome from './welcome'
import Authorization from './authorization'
import Registration from './registration'

const history = createHistory()
const div = document.createElement('div')
document.body.append(div)

ReactDOM.render(
  <Router history={history}>
    <Switch>
      <Route component={Welcome} exact={true} path="/" />
      <Route component={Authorization} exact={true} path="/sign_in" />
      <Route component={Registration} exact={true} path="/sign_up" />
    </Switch>
  </Router>,
  div
)

I have 4 files generated: index.html, main.css, main.js , manifest.js. As you can see, there are 3 pages along the routes and I would like for each page to load its own css / js file + common ones (vendors and manifest), and not one main containing the whole pack of styles / scripts.
The question is how? Or with one entry point this can not be done?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
dummyman, 2017-08-01
@mikor

And why is it necessary? Firstly, uploading one file is much faster than dozens of scanty ones with almost the same empty code template.
If done individually for each page, there may be intersecting code, which, in addition to traffic, will also gobble up RAM again.
For example, the same gzip compression makes sense on files >8kb, otherwise it may not only not compress the code, but also increase it a little. At the same time, one collected common js or css gzip file can easily compress 10 times.
Collecting code into shared files is also useful for the server. Even if they are cached by the browser, the browser still sends a request for each file to the web server, which in turn looks in the project folder and tells the browser that the file has not changed. And each access to the HDD eats up its resource and increases the time it takes to navigate the site.
My opinion - if you have less than 20MB of javascript and styles - you should not think about separating them. A big smut and at the same time a minimum of efficiency.

R
Roman Alexandrovich, 2017-08-01
@RomReed

you can create your own css next to each component and include import './yourcss.css'.
thus, for each component, you can write your own styles separately.

V
vaskadogana, 2018-02-26
@vaskadogana

here is a good compilation

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question