简体   繁体   English

如何在 create-react-app 中使用 Sass 和 CSS 模块?

[英]How to use Sass and CSS Modules with create-react-app?

i am using fileName.module.scss to style my react elements我正在使用 fileName.module.scss 来设计我的 React 元素

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;

and this is my scss这是我的 scss

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

i don't know why but scss is not reflecting onto my main element and ideas ?我不知道为什么,但是 scss 没有反映我的主要元素和想法?

thank you谢谢你

You will have to install node-sass in order to work with scss files.您必须安装 node-sass 才能使用 scss 文件。

npm install node-sass --save-dev npm install node-sass --save-dev

Your code seems to be alright as post react 16.8 you can use module css and scss without configuring webpack.您的代码似乎没问题,因为 post react 16.8 您可以在不配置 webpack 的情况下使用模块 css 和 scss。 I would suggest you to check your version of react first.我建议你先检查你的反应版本。 If you are using prior version of react then you would have to eject and configure your webpack in order to use module css and scss.如果您使用的是以前版本的 react,那么您必须弹出并配置您的 webpack 才能使用模块 css 和 scss。

You can go through this documentation你可以通过这个文档

There is also an option of SASS pre-processing using node-sass-chokidar and add "sass:watch": "node-sass-chokidar <scss directory> -o <compiled css directory> --watch" to your scripts to monitor changes.还有一个使用node-sass-chokidar进行 SASS 预处理的选项,并将"sass:watch": "node-sass-chokidar <scss directory> -o <compiled css directory> --watch"到您的scripts以进行监控变化。

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.如果您使用的是默认支持 sass 的最新create-react-app ,我假设Layout.module.scss是一个 scss 文件名。

use import './Layout.module.scss';使用import './Layout.module.scss'; instead of import classes from './Layout.module.scss';而不是import classes from './Layout.module.scss';

then you may directly call the className那么你可以直接调用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要解决这个问题,只需使用classes.content而不是classes.Content

不要这样做......在你的项目按照这里的描述增长之后,这是一个巨大的构建时间的痛苦......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM