参考文章:css
https://github.com/donvan/css-modules
http://www.w3cplus.com/react/css-modules-for-react.htmlhtml
CSS的规则都是全局的,任何一个组件的样式规则,都对整个页面有效。react
产生局部做用域的惟一方法,就是使用一个独一无二的class
的名字,不会与其余选择器重名。这就是 CSS Modules 的作法。webpack
下面是一个React组件App.js
。git
import React from 'react'; import style from './App.css'; export default () => { return ( <h1 className={style.title}> Hello World </h1> ); };
上面代码中,咱们将样式文件App.css
输入到style
对象,而后引用style.title
表明一个class
。github
.title { color: red; }
构建工具会将类名style.title
编译成一个哈希字符串。web
<h1 class="_3zyde4l1yATCOkgn-DBWEL"> Hello World </h1>
App.css
也会同时被编译。工具
._3zyde4l1yATCOkgn-DBWEL { color: red; }
这样一来,这个类名就变成独一无二了,只对App
组件有效。插件
------------------------code
CSS Modules 提供各类插件,支持不一样的构建工具。本文使用的是 Webpack 的css-loader
插件,由于它对 CSS Modules 的支持最好,并且很容易使用
如何 开启?
加?modules 表示开启css modules功能
几个功能点: 全局样式,样式组合,定制哈希类名,支持变量。