WindiCss在webpack+vue-cli的实践(三)指令

170 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第3天,点击查看活动详情

前言

上一章可以看出来,在写法上有很多重复的地方,但这是有解决方法的,而这个解决方法就是指令

@apply

<div class="w-10px h-10 mt-10px bg-[#000]"></div>
<div class="w-20px h-10 mt-10px bg-[#000]"></div>
<div class="w-30px h-10 mt-10px bg-[#000]"></div>
<div class="w-1rem h-10 mt-10px bg-[#000]"></div>
<div class="w-2rem h-10 mt-10px bg-[#000]"></div>
<div class="w-3rem h-10 mt-10px bg-[#000]"></div>

这一块代码,存在大量重复的h-10,mt-10px,bg-[#000]

那么现在就是要将这些重复代码给提取出来,利用指令

将 @apply 使用在你 style 块中同一行的、一些已存在的工具类上,就可以把这些属性添加到指定class身上

接下来把这块代码替换成

html:

<div class="w-10px item"></div>
<div class="w-20px item"></div>
<div class="w-30px item"></div>
<div class="w-1rem item"></div>
<div class="w-2rem item"></div>
<div class="w-3rem item"></div>

style:

.item {
    @apply h-10 mt-10px bg-[#000];
}

这样将会渲染为

.item {
  background: #000;
  height: 2.5rem;
  margin-top: 10px;
}

!important

需要添加!important,可以直接添加到末尾

.item {
    @apply h-10 mt-10px bg-[#000] !important;
}

@screen

又或者是在@apply中添加媒体查询

@screen sm {
  .custom {
    @apply text-lg;
  }
}

这是官方例子,其中的smlg,默认为

  1. @screen sm:min-width: 640px
  2. text-lg:font-size: 1.125rem; line-height: 1.125rem;

我们很有可能会需要自己配置,那么事实上我们是可以进行自定义配置的

接下来我们可以在windicss.config.js中进行媒体查询的尺寸和字体大小进行配置

windicss.config.js:

export default {
  theme: {
    screens: {
      'sm': { min: '1024px' },
    },
    fontSize: {
      'base': '1rem',
      'lg': '14px',
    },
  },
}

当配置了这个之后,重启一下项目,这个时候将被渲染为:

@media (min-width: 1024px) {
  .custom {
    font-size: 14px;
  }
}

通过实践,发现几点需要注意的地方 :

  1. lg因为重新进行了配置,原来的line-height也因为自定义中没有配置,则被直接替换没了
  2. 当我配置了lg之后,小于lg的未配置,默认的也会被干掉,比如这里配置了lg,则sm, xs的默认配置将会直接被干掉