- px 固定的单位,不会进行自适应。
- rem r = root font-size=16px 1rem=16px,但是需要手动进行单位的换算
- vw vh 相对于视口的尺寸,不同于百分比(相对于父元素的尺寸)375屏幕 1vw = 3.75px
利用插件进行 px(设计稿)=> viewport。
vite 内置了 PostCss 。
Declaration(node) {console.log(node.prop,node.value)
},
具体实现
- 清除默认样式
<!doctype html>
<html lang="en">
<head><meta charset="UTF-8"/><link rel="icon" type="image/svg+xml" href="/vite.svg"/><meta name="viewport" content="width=device-width, initial-scale=1.0"/><title>Vite + Vue + TS</title><style>* {padding: 0;margin: 0;}html, body, #app {height: 100%;overflow: hidden;}</style>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
- 写个圣杯布局(三栏布局)
<template><header><div class="left">left</div><div class="center">center</div><div class="right">right</div></header>
</template><script setup lang="ts"></script><style scoped lang="less">
header {display: flex;.left {width: 100px;height: 50px;background: lightblue;}.center {flex: 1;height: 50px;background: lightcoral;}.right {width: 100px;height: 50px;background: lightgoldenrodyellow;}
}
</style>
- 忽略一些不必要的报错
tsconfig.node.json
{"compilerOptions": {"composite": true,"skipLibCheck": true,"module": "ESNext","moduleResolution": "bundler","allowSyntheticDefaultImports": true,"noImplicitAny": false},"include": ["vite.config.*","plugins/**/*"]
}
- 编写插件
// vite 内置了 postcss 插件,无需安装
import {Plugin} from "postcss";const Options = {viewPortWidth: 375 // UI设计稿的宽度,给多少写多少
}interface Options {viewPortWidth: number
}export const PostcssPxToViewport = (options: Options = Options): Plugin => {const opt = Object.assign({}, Options, options)return {postcssPlugin: 'postcss-px-to-viewport',Declaration(node) {// 这里的px可以写成自定义任意单位,保证只有部分单位需要转换if (node.value.includes('px')) {const num = parseFloat(node.value)node.value = `${((num / opt.viewPortWidth) * 100).toFixed(2)}vw`}},}
}
- vite配置
vite.config.ts
export default defineConfig({plugins: [vue()],// 通过配置变为全局通用样式css: {preprocessorOptions: {scss: {additionalData: '@import "./src/bem.scss";',},},postcss: {plugins: [PostcssPxToViewport()]}}
})