本文介绍了如何在 Create React App 脚手架中使用 CSS Modules 的两种方式。css
请先进行全局安装 create-react-app 插件哈,安装命令:npm install create-react-app -greact
# 使用 npx
$ npx create-react-app my-app
# 使用 npm
$ npm init npx create-react-app my-app
# 使用 yarn
$ yarn create react-app my-app
复制代码
$ cd my-app
# 使用 npm
$ npm start
# 或者使用yarn
# yarn start
复制代码
在浏览器中输入 http://localhost:3000
查看项目效果webpack
create-react-app 中内置了使用 CSS Modules 的配置,当前方式就是使用 create-react-app 内置的用法web
将全部的 .css/.lee/.scss 等样式文件都修改为 .module.css/.module.less/.module.scss 等。便可使用 CSS Modules 的方式进行引入使用了。npm
.error {
background-color: red;
}
复制代码
.error {
color: red;
}
复制代码
import React, { Component } from 'react';
import styles from './Button.module.css'; // 使用 CSS Modules 的方式引入
import './another-stylesheet.css'; // 普通引入
class Button extends Component {
render() {
// reference as a js object
return <button className={styles.error}>Error Button</button>;
}
}
复制代码
此时 Button 组件的背景颜色是红色,可是字体颜色却不是红色,由于使用了 Css Modules 以后,普通的 css 样式就不起效果了,须要用全局的方式编写才能够(:global)。 最后添加到元素上的样式结果为:<button class="Button_error_ax7yz">Error Button</button>
浏览器
在命令行运行 npm run eject
命令sass
此命令会将脚手架中隐藏的配置都展现出来,此过程不可逆bash
运行完成以后,打开 config 目录下的 webpack.config.js 文件,找到 test: cssRegex
这一行app
在 use 属性执行的方法中添加 modules: true
,以下图: less
和第一种方式的用法一致,只是不须要在 css 文件后面加 .module 后缀了
.error {
background-color: red;
}
复制代码
.error {
color: red;
}
复制代码
import React, { Component } from 'react';
import styles from './Button.css'; // 能够直接使用 CSS Modules 的方式引入了
import './another-stylesheet.css'; // 普通引入
class Button extends Component {
render() {
// reference as a js object
return <button className={styles.error}>Error Button</button>;
}
}
复制代码
此时 Button 组件的背景颜色是红色,可是字体颜色却不是红色,由于使用了 Css Modules 以后,普通的 css 样式就不起效果了,须要用全局的方式编写才能够(:global)。 最后添加到元素上的样式结果为:<button class="Button_error_ax7yz">Error Button</button>
如想使用第二种方式对 sass 和 less 也使用 CSS Modules 的方式进行引用,则相似的在 sass 和 less 解析配置上也添加modules: true
便可。
默认 create-react-app 脚手架不能直接使用 sass 和 less 直接编写 css,须要先进行相应配置。
关于如何在 create-react-app 脚手架中启用 sass 和 less 语法,可参考个人下一篇文章: