vue移动端项目中自动将px转rem

113 阅读1分钟

1、安装amfe-flexible,用于自动设置根节点字体大小

npm install amfe-flexible --save

2、在main.js中引入

import 'amfe-flexible/index.min.js'

3、安装 postcss-pxtorempostcss-pxtoremPostCSS的插件,用于将像素单元生成rem单位。

npm install postcss-pxtorem --save

4、在根目录寻找.postcssrc.js文件,如果没有就自己新建,有的项目是postcss.config.js文件,更改内容如下

module.exports = {
  plugins: {   
     "autoprefixer": {  //浏览器版本可加可不加      
        browsers: ["Android >= 5.0", "iOS >= 8"]     
      },    
    "postcss-pxtorem": {      
        rootValue: 75,  // 设计稿以宽度750px为例,设计稿多少就除以10即可      
        selectorBlackList: [".van-"], //排除,van-开头的class,不进行rem转换,UI组件不进行更换      
        propList: ["*"]  //所有文件都进行更换
    } 
  }
}

5、注:在样式中,大写P开头的像素不进行转换

转换前

.demo{
  width: 200px;
  height: 200Px;
  color: #fff;
  background: #ccc;
  text-align: center;
  line-height: 200px;
  font-size: 20px;
}

转换后

.demo{
  width: 2.66667rem;
  height: 200Px;
  color: #fff;
  background: #ccc;
  text-align: center;
  line-height: 2.66667rem;
  font-size: 0.26667rem;
}