一. 简介
css module引入了局部作用域和模块依赖。它的原理是编译成独一无二的class类名,不会与其他选择器重名。
css module 提供各种插件,支持不同的构建工具。比如webpack的css-loader插件,需要配置成'css-loader?module'开启module模式。
二. 全局作用域
css module可以通过配置:global(classname),来声明一个全局的class。其原理就是凡是这种带有global的classname都不会被编译成哈希字符串,使其在全局起作用。
eg: :gloabl(.float_l) { float: left };
三. 局部作用域
cdd module通过将类名或者id名编译成哈希字符串,使其之间不会相互冲突,达到生成局部作用域的目的。
eg: .title { color: blue; } // ./index.css
import style from './index.css';
<h1 className={ style.title }>蓝色的字</h1> // ./index.js
以上,构建工具会吧index.css中的title编译成哈希字符串,同时index.js中对title的引用也会被编译成对应的哈希字符串。达到不和其他类名冲突的目的。
css module 还提供了一种显示的局部作用域写法: :local(.className)。
四. 定制哈希类
css module插件的哈希是可以定制的。通过配置css module插件。比如通过配置css-loader插件。
eg: css-loader?module&localIdentName=[path][name]-[local]-[hash:base64:5]
五. 类名(class)的组合(继承)
在css module中,提供选择器之间相互继承的规则。比如让 .title继承.className
eg: .className: { font-size: 10px }; .title { composes: className ; color: red };
如上:此时title中就有了font-size:10px;这样的属性。
也可以继承自其它模块
eg: .title { composes: className from './other.css' } ;
如上就让当前css文件中的title类继承了other文件下的className类的属性了。
六. 输入变量
css module在postCSS的支持下,可以定义变量。需要配置postcss相关插件。
eg: @value blue: #0c77f8; .title { color: blue };
此时title就相当于color: '#0c77f8';