method one:
create-react-app内置CSS Modules配置
设置style.module.css文件
.css{
background-color:red;
}
在主组件App.js引入css文件
import style form “./style.module.css”;
在组件内部元素里面使用
className={style.css}
tips:此时普通样式就不起效果了,需要用全局的方式去编写(:global)
:global(.App){
text-align:center;
}
method two:
npm run eject 弹出config配置文件
注意:这是一个单项操作,不可逆
修改config/webpack.config.js文件找到如下内容
在use属性执行的方法中添加 modules:true
{
test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
modules: true,
sourceMap: isEnvProduction && shouldUseSourceMap,
})
现在你的css文件不需要加上.module的后缀了,直接可以使用
设置style.css
.css{
font-size: 24px;
color: yellowgreen;
}
在主组件App.js引入css文件
import style form “./style.css”;
在组件内部元素里面使用
className={style.css}
method three:
npm install sass-loader node-sass --save-dev
create-react-app内置支持scss
设置style.module.css文件
$color : blue;
.css {
font-size: 24px;
color: $color;
}
在主组件App.js引入css文件
import style from “./style.module.scss”;
在组件内部元素里面使用
className={style.css}