最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use Sass and CSS Modules with create-react-app? - Stack Overflow

programmeradmin0浏览0评论

I am using FileName.module.scss to style my react elements like so:

// this is my component
import React from "react";

import Aux from '../../hoc/Aux';
import classes from './Layout.module.scss';

const layout = (props) => (
    <Aux>
        <div>Toolbar, SideDrawer, Backdrop</div>
        <main className={classes.Content}>
            {props.children}
        </main>
    </Aux>
);

export default layout;

This is my SCSS:

.Content {
    margin-top: 72px;
    color:red;
}

I don't know why but the scss is not being applied to my main element, any ideas? Thank you!

I am using FileName.module.scss to style my react elements like so:

// this is my component
import React from "react";

import Aux from '../../hoc/Aux';
import classes from './Layout.module.scss';

const layout = (props) => (
    <Aux>
        <div>Toolbar, SideDrawer, Backdrop</div>
        <main className={classes.Content}>
            {props.children}
        </main>
    </Aux>
);

export default layout;

This is my SCSS:

.Content {
    margin-top: 72px;
    color:red;
}

I don't know why but the scss is not being applied to my main element, any ideas? Thank you!

Share Improve this question edited Sep 16, 2021 at 13:40 Dave Mackey 4,43221 gold badges83 silver badges144 bronze badges asked Jan 10, 2020 at 17:08 Lamis AbouzinaLamis Abouzina 4091 gold badge4 silver badges17 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 13

You will have to install node-sass in order to work with scss files.

npm install node-sass --save-dev

Your code seems to be alright as post React 16.8 you can use css and scss modules without configuring webpack. I would suggest you check your version of React first. If you are using a version of React < 16.8 then you would have to eject and configure your webpack in order to use css and scss modules.

If you are using Vite then it supports CSS Pre-processors. download Sass and use it.

Step1: download sass

npm i sass

Step 2: Create a Sass Module file

touch app.module.scss
/*inside app.module.scss*/
.container{
  ...
 }

Step 3: Import it and use

//inside app.tsx/jsx
import style from './app.module.scss
<!--Inside the component-->
<div className={style.container}>
  .....
</div>

If you are using the latest create-react-app which support sass by default, and I assume Layout.module.scss is a scss file name.

use import './Layout.module.scss'; instead of import classes from './Layout.module.scss';

then you may directly call the className

<main className={Content}>
 {props.children}
</main>

I see you're following the same course as me. To fix the issue just use classes.content instead of classes.Content

Dont do it... it's a pain of huge build times after your Project grows as described here...

发布评论

评论列表(0)

  1. 暂无评论