在Create React App中使用CSS Modules的方法示例

本文介紹瞭如何在 Create React App 腳手架中使用 CSS Modules 的兩種方式。有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。

前提條件

請先進行全局安裝 create-react-app 插件哈,安裝命令:npm install create-react-app -g

先使用 create-react-app 命令下載一個腳手架工程,安裝命令:

# 使用 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 查看項目效果

使用 CSS Module 的第一種方式

create-react-app 中內置了使用 CSS Modules 的配置,當前方式就是使用 create-react-app 內置的用法

方式

將所有的 .css/.lee/.scss 等樣式文件都修改成 .module.css/.module.less/.module.scss 等。即可使用 CSS Modules 的方式進行引入使用了。

用法

編寫一個 css 文件:Button.module.css

.error {
  background-color: red;
}

在編寫一個普通的 css 文件:another-stylesheet.css

.error {
  color: red;
}

在 js 文件中使用 CSS Modules 的方式進行引用:Button.js

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>

使用 CSS Module 的第二種方式

方式

在命令行運行 npm run eject 命令

此命令會將腳手架中隱藏的配置都展示出來,此過程不可逆

運行完成之後,打開 config 目錄下的 webpack.config.js 文件,找到 test: cssRegex 這一行

在 use 屬性執行的方法中添加 modules: true ,如下圖:

 

用法

和第一種方式的用法一致,只是不需要在 css 文件後面加 .module 後綴了

編寫一個 css 文件:Button.css

.error {
  background-color: red;
}

再編寫一個普通的 css 文件:another-stylesheet.css

.error {
  color: red;
}

在 js 文件中使用 CSS Modules 的方式進行引用:Button.js

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,需要先進行相應配置。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章