首先在项目根目录创建 postcss.config.js 文件:

module.exports = {
  plugins: {
    'postcss-pxtorem': {
      rootValue({ file }) {
        return file.indexOf('vant') !== -1 ? 37.5 : 75;
      },
      propList: ['*'],
      selectorBlackList: ['.norem'],  // 不转换的类名
      exclude: /node_modules\/(?!vant)/i  // 排除node_modules下除了vant的依赖
    }
  }
}

安装必要的依赖:

npm install amfe-flexible postcss-pxtorem -D

如果使用了 TypeScript,需要在 vite-env.d.ts 中添加类型声明:

/// <reference types="vite/client" />

declare module 'postcss-pxtorem'

现在你的样式中的 px 单位会自动转换为 rem。比如:

  • 16px 会被转换为 0.427rem
  • 60px 会被转换为 1.6rem

注意事项:

  • 如果某些样式不想转换为 rem,可以添加 /*no*/ 注释
  • .example {
      font-size: 16px; /*no*/
    }

    或者使用 norem 类名:

  • .norem {
      font-size: 16px;
    }

    在 main.ts 中引入 amfe-flexible:

  • import 'amfe-flexible'

    如果使用 TypeScript,在 tsconfig.json 中添加类型声明:

  • {
      "compilerOptions": {
        "types": [
          "vite/client",
          "node"
        ]
      }
    }

    在 vite.config.ts 中确保已经配置了 postcss:

  • import { defineConfig } from 'vite'
    import vue from '@vitejs/plugin-vue'
    import postcsspxtorem from 'postcss-pxtorem'
    
    export default defineConfig({
      plugins: [vue()],
      css: {
        postcss: {
          plugins: [
            postcsspxtorem({
              rootValue({ file }) {
                return file.indexOf('vant') !== -1 ? 37.5 : 75;
              },
              propList: ['*'],
              selectorBlackList: ['.norem']
            })
          ]
        }
      }
    })

  • 设计稿如果是 750px 宽度,则普通页面用 75 作为 rootValue
  • Vant 组件使用 37.5 作为 rootValue
  • 这样配置后,你在写样式时直接按照设计稿的 px 值写就可以了,会自动转换为 rem
  • .example {
      width: 100px;  /* 会自动转换为对应的 rem 值 */
    }

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐