postcss-pxtorem

​​​​​​PostCSS 的一个插件,可以从像素单位生成 rem 单位。

amfe-flexible

amfe-flexible是配置可伸缩布局方案,主要是将1rem设为viewWidth/10

1、安装

npm install postcss-pxtorem --save
npm install amfe-flexible --save
npm install autoprefixer --save

2、main.js中引入

import 'amfe-flexible'

3、vite.config.js中配置 我这里引入了vant4 注意要忽略vant 不进行rem转换

import { fileURLToPath, URL } from "node:url";

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import Components from "unplugin-vue-components/vite";
import { VantResolver } from "unplugin-vue-components/resolvers";
import autoprefixer from "autoprefixer";
import postCssPxToRem from "postcss-pxtorem";
// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    Components({
      resolvers: [VantResolver()],
    }),
  ],
  css: {
    postcss: {
      plugins: [
        autoprefixer({
          overrideBrowserslist: [
            "Android 4.1",
            "iOS 7.1",
            "Chrome > 31",
            "ff > 31",
            "ie >= 8",
          ],
        }),
        postCssPxToRem({
          // 自适应,px>rem转换
          rootValue: 75, // 75表示750设计稿,37.5表示375设计稿
          propList: ["*"], // 需要转换的属性,这里选择全部都进行转换
          selectorBlackList: [".van"], // 过滤掉van-开头的class,不进行rem转换
          exclude: "/node_modules", // 忽略包文件转换rem
        }),
      ],
    },
  },
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
    },
  },
});

接下来我们随便写个盒子

 浏览器会自动转换rem

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐