Reputation: 1975
I am using TypeScript with React on Rails.
My SCSS file is in same folder with tsx files and this scss file import all necessary modules. So i have a one big css file at the end.
I also have 42 components. Every component has a html code that renders. So, I import styles in components like this:
import * as styles from 'main.module.scss';
Problem is, my page loads fast. But styles are delayed a bit. At first i see html dom object without styles then styles applied. This wonders me that, does React loads my scss styles 42 times or just once and re-use on each components?
If not how can i globally import styles
and use across all components?
sample component
import * as styles from 'main.module.scss';
...
render() {
return (
<div className={styles.container}>
<div className={styles.pageInner}>
content...
</div>
</div>
)
}
Upvotes: 0
Views: 6570
Reputation: 5743
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>
}
Upvotes: 1
Reputation: 2033
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
Upvotes: 0
Reputation: 945
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.
Upvotes: 0