一、前言

之前项目中一直使用的是 postcss-pxtoremlib-flexible 实现的手机端适配问题。

不经意间看到 lib-flexible 中的如下描述:

由于 viewport 单位得到众多浏览器的兼容,lib-flexible 这个过渡方案已经可以放弃使用,不管是现在的版本还是以前的版本,都存有一定的问题。建议大家开始使用 viewport 来替代此方。

便开始寻找 postcss 针对 viewport 相关的插件。

二、postcss-px-to-viewport

px 单位转换为视口单位的(vw, vh)PostCSS 插件

官方链接

三、Vue 项目中使用

1、安装

  1. yarn add postcss-px-to-viewport -D

2、配置 postcss.config.js 文件

  1. module.exports = {
  2. plugins: {
  3. // ...
  4. 'postcss-px-to-viewport': {
  5. // options
  6. viewportWidth: 750, // 设计稿的视口宽度
  7. // 其余使用默认值即可
  8. }
  9. }
  10. }

options

3. OK 了

四、兼容 Vant 组件库

当我们项目设计稿的视口宽度不等于 375 时。Vant 组件的样式会有所影响。因为 Vant 是按 375 的设计来的。

这时修改 postcss.config.js 文件如下即可。

  1. module.exports = ({ file }) => {
  2. const designWidth = file.dirname.includes("node_modules/vant") ? 375 : 750;
  3. return {
  4. plugins: {
  5. "postcss-px-to-viewport": {
  6. viewportWidth: designWidth,
  7. },
  8. },
  9. };
  10. };