what's the main diffrence style.scss vs style.module.scss?
Asked Answered
C

2

17

I'm using react with sass.

It's look like both have same benefits. Locally scoped, No more conflict etc. What is the main diffrence between style.scss vs style.module.scss

Why do we need .module prefix?

Candlemaker answered 18/3, 2020 at 7:28 Comment(0)
S
34

Short Answer

*.scss is normal SCSS file while *.module.scss is SCSS file with CSS modules.

According to the repo, CSS modules are:

CSS files in which all class names and animation names are scoped locally by default.

This solves the problem of typing ultra specific CSS class names to avoid clashes. Good bye .phone-page-contact-form-edit-card-default-button-blah-blah and hello .default-button

Usage

Below is the usage for *.scss

.ultra-specific-class-name_item {
  display: flex;
}

If you use SCSS in a normal way, you must declare the class name as a string

// Simply import
import './foo.scss';


const App = () => (
  <div className="ultra-specific-class-name_item">
    foo bar
  </div>
)

Below is the usage for *.module.scss

// No need of any ultra specific classnames 
.item {
  display: flex;
}

If you use SCSS as a CSS module, you must use them as how you would use a JS module.

// import as a js module 
import styles from './foo.module.scss';

const App = () => (
  <div className={styles.item}>
    foo bar
  </div>
)

Output

<!-- Normal SCSS -->
<!-- it will not be transformed -->
<div class="ultra-specific-class-name_item">foo bar</div>

<!-- SCSS with Class Module -->

<!-- hash values are suffixed to the class name -->
<div class="item-35ada5">foo bar</div>

<!-- newer versions will even prefix the file name
     to the class name -->
<div class="foo__item-35ada5">foo bar</div>
Sage answered 18/3, 2020 at 9:4 Comment(3)
can you explain what is the advantage of doing .module.scss? I don't get the usage it is currently breaking my styles if i try to import with import fiename.scssDeckhand
SCSS module files are scoped, meaning styles defined in that file will not interfere with other files and there's no need for us to name classes as .phone-page-contact-form-edit-card-default-button-blah-blah just default-button is enough.Sage
Check this article css-tricks.com/css-modules-part-1-needSage
Y
0

I notice a difference that .module.scss prevents simple import

// does not work
import './foo.module.scss';

.module.scss forces you to import as module

// works
import styles from './foo.module.scss';

and I didn't find difference between below codes. (I didn't use features like composes)

import styles from './foo.module.scss';

import styles from './foo.scss';
Yelena answered 15/12, 2023 at 5:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.