Vue-CLI中配置postcss-pxtorem自动将px转换为rem

1.安装postcss-pxtorem

$ npm install postcss postcss-pxtorem --save-dev

2.添加配置项package.json

{
  "name": "myweb",
  "version": "0.1.0",
  "private": true,
  //...
  "postcss": {
    "plugins": {
      "autoprefixer": {},
      "postcss-pxtorem": {
        "rootValue": 37.5,
        "propList": [
          "*"
        ]
      }
    }
  },
 //...
}

3.创建src/utils/rem.js

window.onresize = function () {
    getSize();
};
function getSize  () {
    var deviceSize = document.documentElement.clientWidth;
    console.log("设备宽度:", deviceSize);
    var fontSize = (deviceSize / 20);  
    // 这里的 20 * rootValue = 你的设计稿宽度px
    // 例如我的设计稿宽750px : 20 *  rootValue(37.5) = 750px
    console.log("字体大小:",fontSize +"px");
    document.documentElement.style.fontSize = fontSize +"px";
}
getSize(); // 这里必须在页面打开时先执行一次

4.main.js 导入rem.js

import "./utils/rem.js"

5.总结

postcss-pxtorem只是一个方便开发的插件,你可以在源码中直接写设计稿单位xp。在调试、开发打包时自动转换为rem。在Vue-Cli中项目中默认自带安装了Postcss,只需要配置和动态修改DOM根元素fontSize。Vue-Cli会帮你自动完成.

This entry was posted in js, Vue. Bookmark the permalink.

发表回复