用的css预处理器用sass,其他大同小异。
用create-react-app创建项目,执行npm run eject弹出配置文件(此操作不可逆);
配置sass,用的最新的CRA,webpack4;
webpack.config.dev.js (webpack.config.prod.js需相同配置一份):
module下的rules 中 oneOf 修改&增加
{ // Exclude `js` files to keep "css" loader working as it injects // its runtime that would otherwise processed through "file" loader. // Also exclude `html` and `json` extensions so they get processed // by webpacks internal loaders. exclude: [/.(js|jsx|mjs)$/, /.html$/, /.json$/, /.sass$/, /.scss$/], loader: require.resolve('file-loader'), options: { name: 'static/media/[name].[hash:8].[ext]', }, }, { test: /.(scss|sass)$/, use: [ 'style-loader', { loader: 'css-loader', options: { importLoaders: 1,modules: true } }, 'sass-loader' ] // loaders: ['style-loader', 'css-loader', 'sass-loader'] }
其中modules: true 意思是开启模块化css处理
css:
.body border: 1px solid red .body-wrapper border: 2px solid red
页面引入:
import indexCss from '../../css/style.scss';
使用:
className={indexCss.body}
className={indexCss["body-wrapper"]}
注意className带符号的 要用indexCss["body-wrapper"]这种形式
效果可以看到 class name都加上了编译:
有些样式不需要编译,就要:global(className)来标识这个类是全局类名,因此CSS Modules不对其类名进行转化:
结构:
import React, { Component } from "react"; import indexCss from '../../css/style.scss'; export default class Index extends Component{ render() { return( <div className={indexCss["body-wrapper"]}> <div className={indexCss.body}> <span>关于我们</span> <span className={indexCss.name}>name</span> </div> <div className="title">title标题</div> </div> ); } }
样式:
.body{ border: 1px solid red; } .body-wrapper{ padding: 50px; border: 2px solid red; .name{ color: red; } } :global(.title) { color: blue }
效果: