score:0

are you using webpacker or a similar gem to manage this? webpack is smart enough to reuse imports - it won't include it a ton of times.

that said, since css is global, you only need to import main.scss once anyway, at the top level.

score:0

since you are using webpack, one option would be to compile scss to plain css and include it as a stylesheet in the root html page, most likely, index.html

score:1

does react loads my scss styles 42 times

i just did the experiment, the answer is no. although this, it is still not recommended to put all styles in a file. i think you should separate your main.module.scss to many small files.

there are 2 kinds of css style.

one is a global style which shared by multiple components, for example, you define it in global.scss file, this file is just needed to import once at the top level js file.

// global.scss
.container {
  padding: 10px;
}

// applicaiton.js
import "global.scss"

// examplecomponent.jsx, don't need to import "global.scss"
// classname should be the string
...
render() {
  return <div classname='container'>example</div>
}

another one is a module style which is only used by a component or a very few components, and it should just include the styles only used in the target component, it is usually small and has the same name as the component.

// examplecomponent.module.scss
.container {
  margin: 10px;
}

 // examplecomponent.jsx
import * as styles from 'examplecomponent.module.scss'

...
render() {
  return <div classname={styles.container}>example</div>
}

if you want to mix the global style and module style in the same element, you can use classnames npm or like this:

 // examplecomponent.jsx
import * as styles from 'examplecomponent.module.scss'

...
render() {
  return <div classname={`container ${styles.container}`}>example</div>
}

Related Query

More Query from same tag