Vue3自定义PostCss插件
- 插件功能: 实现自动转px为vw功能
- 1. 创建插件ts文件
- 2. tsconfig.node.json引入插件
- 3. vite.config.ts增加插件配置
- 4. 编写插件内容
- 5. 示例
插件功能: 实现自动转px为vw功能
px 固定单位,不会随着屏幕的变化而变化
vh vw 相对于视口高宽进行控制
1. 创建插件ts文件
2. tsconfig.node.json引入插件
"include": ["vite.config.ts","plugins/**/*"]
3. vite.config.ts增加插件配置
import { PostCssToViewport } from './plugins/postcss-px-to-viewport'// https://vitejs.dev/config/
export default defineConfig({plugins: [vue(),vueJsx()],css:{//配置自定义postcss插件postcss:{plugins:[PostCssToViewport()]},},})
4. 编写插件内容
//postcss插件
import { Plugin } from "postcss"const Options = {viewportWidth: 375,//默认视口宽度
}
interface Options {viewportWidth?:number
}export const PostCssToViewport = (options:Options = Options):Plugin =>{const opt = Object.assign({},Options,options);return {postcssPlugin: 'postcss-px-to-viewport',//钩子函数Declaration(node){//判断需要转换的单位if(node.value.indexOf('xm') != -1){console.log(node.prop,node.value);const num = parseFloat(node.value);node.value = `${((num / opt.viewportWidth)*100).toFixed(2)}vw`}}}
}
插件会将样式中是自定义单位(xm)装换为vw
5. 示例
<template><div><header class="header"><div>left</div><div>center</div><div>right</div></header></div>
</template><script setup lang=ts>
import {ref} from 'vue'</script><style scoped lang="less">.header{display: flex;div{height: 50px;line-height: 50px;color: #fff;text-align: center;}div:nth-child(1){width:100xm;background-color: #f00;}div:nth-child(2){flex:1;background-color: #0f0;}div:nth-child(3){width: 100xm;background-color: #00f;}
}
</style>