vue自适应postcss-pxtorem + amfe-flexible

vue自适应postcss-pxtorem + amfe-flexible

  • 安装amfe-flexible和postcss-pxtorem
  • 配置及使用
      • webpack配置
      • vite配置
  • 可能遇到问题

安装amfe-flexible和postcss-pxtorem

npm install postcss-pxtorem
npm install amfe-flexible

postcss-pxtorem将px转为rem;
amfe-flexible可进行屏幕自适应;

配置及使用

  1. 在main.js中引入amfe-flexible
import  "amfe-flexible";
  1. 根目录下添加postcss.config.js

webpack配置

module.exports = () => ({
  plugins: [
  	// autoprefixer 自动补齐 CSS3 前缀,适配不同浏览器
    require('autoprefixer')({
      overrideBrowserslist: [
        "last 10 versions", // 所有主流浏览器最近10版本用
      ],
    }),
    require('postcss-pxtorem')({
      rootValue: 192.0, //设计稿元素尺寸/10,这里设计稿宽度为1920
      propList: ["*"], //是一个存储哪些将被转换的属性列表,这里设置为['*']全部,假设需要仅对边框进行设置,可以写['*', '!border*']
      unitPrecision: 3, //保留rem小数点多少位
      selectorBlackList: ['el-input', 'el-step', 'no-'],//则是一个对css选择器进行过滤的数组,比如你设置为['el-'],那所有el-类名里面有关px的样式将不被转换,这里也支持正则写法。
      replace: true, 
      mediaQuery: false, //媒体查询( @media screen 之类的)中不生效
      // minPixelValue: 3, //px小于3的不会被转换
    })
  ]
});

vite配置

export default {
    'plugins': {
        'autoprefixer': {
            overrideBrowserslist: [
                'Android 4.1',
                'iOS 7.1',
                'Chrome > 31',
                'not ie <= 11',  //不考虑IE浏览器
                'ff >= 30', //仅新版本用“ff>=30
                '> 1%',//  全球统计有超过1%的使用率使用“>1%”;
                'last 2 versions', // 所有主流浏览器最近2个版本
            ],
            grid: true,// 开启grid布局的兼容(浏览器IE除外其他都能兼容grid,可以关闭开启)
        },
        'postcss-pxtorem': {
            rootValue: 37.5, // 设计稿宽度除以 10,  开头大写的Px 不转换 => height: 100Px, 内联样式不转换,需要 / 75 转成 rem
            unitPrecision: 2, // 计算结果保留 6 位小数
            selectorBlackList: ['.no-rem', 'no-rem'], // 要忽略的选择器并保留为px。
            propList: ['*'], // 可以从px更改为rem的属性  感叹号开头的不转换
            replace: true, // 转换成 rem 以后,不保留原来的 px 单位属性
            mediaQuery: true, // 允许在媒体查询中转换px。
            minPixelValue: 2, // 设置要替换的最小像素值。
            exclude: /node_modules/i // 排除 node_modules 文件(node_modules 内文件禁止转换)
        }
    }
}

配置完成后重启项目

可能遇到问题

  1. 运行报错如下
Error: PostCSS plugin postcss-pxtorem requires PostCSS 8.

此报错是指需要使用postcss-pxtorem 8的版本,但是postcss-pxtorem版本最高才6.0
所以此时对postcss-pxtorem版本进行降低到5.1.1

npm i postcss-pxtorem@5.1.1

再次运行就可以了

你可能感兴趣的:(vue,vue.js,postcss,javascript)