在Vue的项目中,在vue页面的style节点,会存在大量的自定义css内容,最好有一个公共的css库来避免这块的失控,所以这就是本篇存在的目的。
一、官方网址
二、安装与配置
pnpm i -D vite-plugin-windicss windicss
vite.config.ts
import WindiCSS from "vite-plugin-windicss"
export default defineConfig({
plugins: [
...
WindiCSS(),
...
]
})
在vite.config.js同级目录下创建windi.config.ts文件,能够被识别。
import { defineConfig } from "windicss/helpers"
export default defineConfig({
})
三、配置项
1. safelist
当className是动态拼接出来时,如<div className={p-${size}}>,不包括boolean ? ' py-8'这种写法:
export default defineConfig({
plugins: [
...
WindiCSS({
safelist: "p-1 p-2 p-3 p-4"
}),
...
]
})
2. attributify
设置为 true,将开启属性模式
import { defineConfig } from "windicss/helpers"
export default defineConfig({
attributify: false,
})
属性模式可以这样写:
<button w="100px" h="40px">btn</button>
为了防止命名冲突,还可以自定义一个前缀
attributify: {
prefix: "w:",
}
属性模式可以这样写:
<button w:w="100px" w:h="40px">btn</button>
attributify不开启,设置为false。
四、main.ts配置
import "virtual:windi.css"
等价于
import 'virtual:windi-base.css'
import 'virtual:windi-components.css'
// 自定义的样式放在这里
import 'virtual:windi-utilities.css'
项目中这样配置:
import 'virtual:windi-base.css'
import 'virtual:windi-components.css'
import './style.css'
import 'virtual:windi-utilities.css'
五、特性案例
1. 引入图片
这个有用。
// windi.config.js
export default defineConfig {
theme: {
extend: {
backgroundImage: theme => ({
'app-bg': 'url('@app/src/assets/img/bg.svg')',
}),
},
},
}
<div bg="app-bg"></div>
2. 响应式
这个也许有用,当PC移动分两个工程时意义不大。
自定义断点:
export default defineConfig({
theme: {
screens: {
phone: '320px',
iPad: '1024px',
sm: '1280px',
md: '1366px',
lg: '1440px',
xl: '1920px',
},
},
})
<div class="phone:bg-red-400 phone:text-light-100 phone:p-10 iPad:p-50 iPad:bg-blue-700 lg:p-100 lg:bg-cyan-800 lg:text-50px">响应式</div>
以上可以把类写成组的形式
<div class="phone:(bg-red-400 text-light-100 p-10) iPad:(p-50 bg-blue-700) lg:(p-100 bg-cyan-800 text-50px)">响应式</div>
3. lg、<lg、@lg
这个有可能在某些情况下有用。
lg => greater or equal than this breakpoint
<lg => smaller than this breakpoint
@lg => exactly this breakpoint range
这主要用来根据具体的属性值来设置对应的样式:
lg:p-1
<lg:p-2
@lg:p-3
4. 指令@apply
这个尽量少用。
<div class="btn btn-blue">button</div>
<style scoped>
.btn {
@apply font-bold py-2 px-4 rounded w-100px m-10px;
}
.btn-blue {
@apply bg-blue-500 hover:bg-blue-700 text-white;
padding-top: 1rem;
}
</style>
5. @variants
这个尽量少用。
<div class="btn-blue btn">button</div>
<style>
.btn {
@apply font-bold py-2 px-4 rounded w-100px m-10px;
}
.btn-blue {
@apply bg-blue-500 hover:bg-blue-700 text-white;
padding-top: 1rem;
}
@variants focus, hover { /** <== */
.btn {
@apply w-200px h-200px;
}
}
@variants dark {
}
</style>
6. @screen
尽量少用
@screen sm {
.custom {
@apply text-lg;
}
}
7. theme()
theme() 函数允许你通过 . 运算符来获取你设置的值
<span class="color-blue">color blue</span>
<style>
.color-blue {
color: theme("colors.blue.400");
}
</style>