简体   繁体   English

如何在 React 16.13.1 中启用 CSS 模块?

[英]How can I enable CSS Modules in React 16.13.1?

everyone.每个人。 I'm trying to watch tutorials and read articles on how to enable CSS Modules in React 16.13.1, I understand that to do this, I must run "npm run eject".我正在尝试观看教程并阅读有关如何在 React 16.13.1 中启用 CSS 模块的文章,我知道要做到这一点,我必须运行“npm runeject”。 which I have done, Next.我已经完成了,下一步。 I know that I have to edit the "webpack.config.js" file, However.我知道我必须编辑“webpack.config.js”文件,但是。 my webpack.config.js file looks very different than those online.我的 webpack.config.js 文件看起来与网上的非常不同。 A snippet of my webpack.config,js file is below?我的 webpack.config,js 文件的片段如下? so what lines must I add and where to enable CSS Modules, If you need more info.所以我必须添加哪些行以及在哪里启用 CSS 模块,如果您需要更多信息。 please let me know.请告诉我。

test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
  importLoaders: 1,
  sourceMap: isEnvProduction && shouldUseSourceMap,
}),

Name your file styles.module.css works in CRA将您的文件命名为 styles.module.css 在 CRA 中工作

Example you create a css file in the same folder as the js file:例如,您在与 js 文件相同的文件夹中创建 css 文件:

MyComponent.我的组件。 module .css模块.css

.Mycomponent {
    padding: 10px; 
    margin: 5px;
}

MyComponent.js我的组件.js

import React from 'react';
import classes from "./MyComponent.module.css";

const MyComponent = () => {
    return (
        <div className={classes.Mycomponent}>
            This div needs some padding and margin
        </div>
    )
}

export default MyComponent

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

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