本文介紹瞭如何在 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 語法,可參考個人下一篇文章: