1. CSS Modules引入目的

  写过CSS的人,应该都对一大长串选择器选中一个元素不陌生吧,这种方式,其实定义的就是全局样式,我们时常会因为选择器权重问题,没有把我们想要的样式加上去。

  另外,每次都需要把所有的样式表都导入到程序中,如果我们可以像使用js模块一样,想用哪块就用哪块,是不是就很理想了。

  CSS Modules就解决了这个问题,它自动为每一个类生成一个哈希值,可以惟一标志这个类,因此避免了我们说的第一个问题,它让我们可以像使用js模块那样,想用哪部分样式,就引入哪部分样式。下面我们来具体介绍它的使用方法。

2.CSS Modules使用方法

  1) 如何在开启CSS Modules

  create-react-app 脚手架 引入 css-modules

modules:true,
localIdentName:'[name]__[local]__[hash:base64:5]'

  webpack.config.dev.js

{
test: /\.less$/,
exclude: /node_modules|antd\.css/,
use: [
require.resolve('style-loader'),
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
modules:true,
localIdentName:'[name]__[local]__[hash:base64:5]'
},
},
{
loader: require.resolve('postcss-loader'),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebookincubator/create-react-app/issues/2677
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
],
flexbox: 'no-2009',
}),
],
},
},
{
loader: require.resolve('less-loader') // compiles Less to CSS
}
],
},
{
test: /\.css$/,
use: [
require.resolve('style-loader'),
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
},
},
{
loader: require.resolve('postcss-loader'),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebookincubator/create-react-app/issues/2677
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
],
flexbox: 'no-2009',
}),
],
},
},
],
},

  webpack.config.prod.js

{
test: /\.less$/,
exclude: /node_modules|antd\.css/,
loader: ExtractTextPlugin.extract(
Object.assign(
{
fallback: {
loader: require.resolve('style-loader'),
options: {
hmr: false,
},
},
use: [
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
modules:true,
localIdentName:'[name]__[local]__[hash:base64:5]',
minimize: true,
sourceMap: shouldUseSourceMap,
},
},
{
loader: require.resolve('postcss-loader'),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebookincubator/create-react-app/issues/2677
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
],
flexbox: 'no-2009',
}),
],
},
},
{
loader: require.resolve('less-loader') // compiles Less to CSS
}
],
},
extractTextPluginOptions
)
),
// Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract(
Object.assign(
{
fallback: {
loader: require.resolve('style-loader'),
options: {
hmr: false,
},
},
use: [
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
minimize: true,
sourceMap: shouldUseSourceMap,
},
},
{
loader: require.resolve('postcss-loader'),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebookincubator/create-react-app/issues/2677
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
],
flexbox: 'no-2009',
}),
],
},
},
],
},
extractTextPluginOptions
)
),
// Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
},

  2)CSS Modules用法

  1.基本使用方法

  在你的项目中,添加一个CSS文件,然后你就可以像引入js模块一样,在你的js文件中引入这个文件存放到一个对象中。这个对象中是一个包含连个属性的对象,其值就是自动生成的类名。这个类名也会替换页面中的类名。

style.scss

/* style.scss */
.bgRed {
background-color: #f00;
}

app/app.js

/* app/app.js */

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
/* 引入我们定义的.scss文件 */
import styles from '../style/style.scss'; /* 使用无状态函数定义我们的组件*/
function Title() {
console.log(styles);
/* 打印引入的styles,是一个包含连个属性的对象,其值就是自动生成的类名
Object {white: "_24PAw-tvdzL8pt4nyAvnJX", bgRed: "_2R9YNZv7rx_o02FHxKTBzC"}
*/
return (
/* 在组件中引用 */
<h1 className={styles.bgRed}>Hello React!</h1>
);
} /* 渲染到页面中 */
ReactDOM.render(<Title />, document.body );

最终页面结构,如下图所示:

  2. 自定义命名规则

  上面生称的类名,完全是自动生成,如果自己自己规定命名规则呢,也是很简单的,只需要在上面配置modules后面添加&localIdentName=配置规则,如:

'css-loader?modules&localIdentName=[name]__[local]-[hash:base64:5]' //style__bgRed-2R9YN,local对应所在文件夹名,local对应文件名,最后是哈希值

  3. 全局类名和本地类名

  我们可以使用:global(className)来标识这个类是全局类名,因此CSS Modules不对其类名进行转化,:local(className)则相反,如果不用这两个包裹的话,默认是local.

style.scss

/* style.scss */
.bgRed {
background-color: #f00;
} // 添加全局bgRed
:global(.bgRed) { }

app/app.js

/* app/app.js */

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
/* 引入我们定义的.scss文件 */
import styles from '../style/style.scss'; /* 使用无状态函数定义我们的组件*/
function Title() {
console.log(styles);
return (
/* 在组件中全局的bgRed,此时我们可以访问到我们全局定义的bgRed,它并没有被转化 */
<h1 className="bgRed"}>Hello React!</h1>
);
} /* 渲染到页面中 */
ReactDOM.render(<Title />, document.body );

  4. 使用composes组合样式

  我们知道,node.js中,我们可以用require引入模块,然后使用它们。CSS Modules也提供了composes来该文件中的样式规则,甚至引用其它文件中的样式规则。

style/style.scss

/* style/style.scss */

.fontWhite {
color: #fff;
}
.bgRed {
composes: fontWhite;
background-color: #f00;
}

app/app.js

/* app/app.js */

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
/* 引入我们定义的.scss文件 */
import styles from '../style/style.scss'; /* 使用无状态函数定义我们的组件*/
function Title() {
console.log(styles);
/* 打印引入的styles,是一个包含连个属性的对象,其值就是自动生成的类名
Object {fontWhite: "style__fontWhite-3jipu", bgRed: "style__bgRed-2R9YN style__fontWhite-3jipu"}rx_o02FHxKTBzC"}
*/
return (
/* 在组件中引用 */
<h1 className={styles.bgRed}>Hello React!</h1>
);
} /* 渲染到页面中 */
ReactDOM.render(<Title />, document.body )

此时,就是添加了两个类,html结构如下图:

引入其它文件中的样式规则,写composes: className(要引入的类名) from '引入的文件路径即可',最终效果同上,composes多少规则,就添加多少类。

最后:大家有名有发现,我一直都在类上做文章,那是因为CSS Modules只转换class名相关的样式。大家要注意啦。

在最后,给大家提供一个js库——classnames类库,给我的感觉和angular中的ng-class差不多,将值为true的类添加上。

CSS Modules 解决 react 项目 css 样式互相影响的问题的更多相关文章

  1. create-react-app创建react项目 css模块化处理

    用的css预处理器用sass,其他大同小异. 用create-react-app创建项目,执行npm run eject弹出配置文件(此操作不可逆): 配置sass,用的最新的CRA,webpack4 ...

  2. CSS modules 与 React中实践

    最近一直在学习React,看上去蛮简单的内容,其实学习曲线还是比较高的. 目前学到css绑定的问题,看到有一篇好的文章,就转过来了. CSS 模块化的解决方案有很多,但主要有两类.一类是彻底抛弃 CS ...

  3. 解决react项目中跨域和axios封装使用

    最新几天学了一下react,发现了几个问题,估计新入坑的同学们也会遇到,下面我先列出来几点 1.请求跨域问题 2.如何发起请求 3.axios的简单封装 全局安装create-react-app脚手架 ...

  4. styled-components:解决react的css无法作为组件私有样式的问题

    react中的css在一个文件中导入,是全局的,对其他组件标签都会有影响. 使用styled-components第三方模块来解决,并且styled-components还可以将标签和样式写到一起,作 ...

  5. 转 : CSS Modules详解及React中实践

    https://zhuanlan.zhihu.com/p/20495964 CSS 是前端领域中进化最慢的一块.由于 ES2015/2016 的快速普及和 Babel/Webpack 等工具的迅猛发展 ...

  6. css模块化及CSS Modules使用详解

    什么是css模块化? 为了理解css模块化思想,我们首先了解下,什么是模块化,在百度百科上的解释是,在系统的结构中,模块是可组合.分解和更换的单元.模块化是一种处理复杂系统分解成为更好的可管理模块的方 ...

  7. CSS Modules使用方法

    css modules调研 css模块化解决方案 抛弃css (Radium,jsxstyle,react-style) 利用js来管理样式依赖(css Modules) css模块化面临的问题 全局 ...

  8. CSS Modules 与 scoped 的不一样

    What ? css 的作用域表现. Css modules 是一个CSS文件,其中所有类名和动画名称默认为局部作用域. 使用JS编译原生的CSS文件,使其具备模块化的能力,该文件需要import使用 ...

  9. CSS Modules入门教程

    为什么引入CSS Modules 或者可以这么说,CSS Modules为我们解决了什么痛点.针对以往我写网页样式的经验,具体来说可以归纳为以下几点: 全局样式冲突 过程是这样的:你现在有两个模块,分 ...

随机推荐

  1. spring中路径的注入

    @RequestMapping("${mgt}/file") //请求的路径的统一添加,需要在mvc层配置<context:property-placeholder loca ...

  2. chvt - 修改虚拟终端的前台环境

    SYNOPSIS(总览) chvtN DESCRIPTION(描述) chvt N 命令用来生成 /dev/ttyN 的前台终端.如果它本来不存在,即创建相应的屏幕.为了删除掉不用的VT(虚拟终端), ...

  3. CAD参数绘制填充(网页版)

    填充是CAD图纸中不可或缺的对象,在机械设计行业,常常需要将零部件剖开,以表现其内部的细节,而这些被剖开的截面会用填充来表示:在工程设计行业,一些特殊的材料或地形,也会用填充来表示. js中实现代码说 ...

  4. Android反编译初步

    网上关于Android反编译的帖子很多,反编译的步骤也是很详细,本文Android反编译参考博客:https://www.cnblogs.com/dhcn/p/7120891.html 而反编译中最主 ...

  5. 从C#程序中调用非受管DLLs

    从C#程序中调用非受管DLLs 文章概要: 众所周知,.NET已经渐渐成为一种技术时尚,那么C#很自然也成为一种编程时尚.如何利用浩如烟海的Win32 API以及以前所编写的 Win32 代码已经成为 ...

  6. note for git

    1.download https://git-for-windows.github.io/ 2.command add file to git: git add filename & git ...

  7. oracle获取排序后的第一条信息

    查询表table1里字段id小于10的所有数据,并且让数据根据id降序排列,然后得到第一条数据 select * from (select * from table1 where id<10 o ...

  8. [Thu Summer Camp2016]补退选

    题目描述不说了. 题解: Trie+vector…… Trie存学生,vector存答案. 极为无脑但无脑到让人怀疑 代码: #include<cmath> #include<vec ...

  9. 关于C/C++的一些思考(3)

    操作符重载函数(Operator Overload Function)的基本概念: 目的是以与对待内置数据类型相同的方式对待用户自定义类型(程序执行速度会受到影响),限制是不能随意选择函数名和参数个数 ...

  10. 零基础入门学习Python(8)--了不起的分支和循环2

    前言 上节课小甲鱼教大家如何正确的打飞机,其要点是判断和循环,判断就是该不该做某事,循环就是持续做某事 知识点 写一个程序 按照100分制,90分以上成绩为A,80到90为B,60到80为C,60以下 ...