前言
最近学习 webpack 看到了一个新鲜的东西, 之前都是通过 scoped 来区别类名, 秉着任何时候学习都不晚的心情, 作为小白的我也想揭揭 CSS module 的神秘面纱.
CSS module 目的为所有类名重新生成类名, 有效避开了 CSS 权重和类名重复的问题. 相比于 scoped 为类名添加一个 hash 标识效果优秀不少, 但相对的书写会繁琐一些.
项目基于 cli3 搭建, 讲真的, 我也是被 cli3 鬼迷心窍了. 相比 2 的繁琐, 3 提供界面管理对我这样子的小白确实直观很多, 而且需要配置 vue.config.JS 也十分合适呢.
开工
动手之前先配置项目, 网上很多文章说需要下载 CSS-loader 插件, 亲测删掉也能正常运行
在 vue.config.JS 中添加如下配置
- CSS: {
- loaderOptions: {
- CSS: {
- localIdentName: '[name]__[local]-[hash:base64:5]',
- camelCase: true
- }
- }
- }
localIdentName 是格式化类名: name 是当前文件名称, local 是当前定义的类名名, hash 是 hash 生成的字符串, 长度为 5
camelCase: 在类名有中横线时,'only'在标签上绑定类名时只支持大驼峰, true: 支持大驼峰也支持中括号命名
特别注意: CSS module 所有类名都要: class 进行绑定
- <div>
- <p class="less-color"> 这是通过 Less 设置的: global 字体颜色为粉色 </p>
- <p :class="$style.lessFontSize"> 这是通过 Less 设置的: local 字体大小为 40px</p>
- <p :class="$style.red">This should be red</p>
- <h4 :class="$style.headerTit"> 类别推荐 </h4>
- <h4 :class="$style['header-tit']"> 类别推荐 </h4>
- </div>
样式表需要添加 module, 可以通过 console.log(this.$style); 输出当前所有的: local { } 类名. 默认是: local { }, 即: local 前缀是可以省略的, 若要全局类名则资额在: global { } 内
- <style module lang="less">
- :global {
- .Less-color {
- color: pink;
- }
- }
- :local {
- .Less-font-size {
- font-size: 40px;
- }
- .red {
- color: red;
- }
- .header-tit {
- color: blue;
- }
- }
- </style>
后记
过程还是蛮曲折的, 小白就是道阻且长啊, 不过我相信积少成多, 会有蜕变的一天的.
malk 2018.12.3
来源: http://www.jianshu.com/p/125f33c35446