vue-cli3.0 结合 lib-flexible、postcss-px2rem-exclude 实现移动端适配问题

2,332 阅读1分钟

以前移动端适配方法:

    // 根据 750 的设计图来换算。
    (function (doc, win) {
    var docEl = doc.documentElement,
        resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
        recalc = function () {
            var clientWidth = docEl.clientWidth;
            if (!clientWidth) return;
            if (clientWidth >= 750) {
                docEl.style.fontSize = '100px';
            } else {
                docEl.style.fontSize = clientWidth / 7.5 + 'px'; // 1rem = 100px;
            }
        };
    if (!doc.addEventListener) return;
    win.addEventListener(resizeEvt, recalc, false);
    doc.addEventListener('DOMContentLoaded', recalc, false);
})(document, window);

现在想别的适配方式:采用 vue-cli3.0 结合 lib-flexible、postcss-px2rem-exclude 实现移动端适配的方案。 以下为项目搭建成功后的适配方案:

一、安装和引入 lib-flexible

    // 安装
    npm install lib-flexible --save
    
    // 项目入口 main.js 文件中引入
    import 'lib-flexible'

二、安装和配置 post-px2rem-exclude

引入 vant 组件库时,因第三库 css是依据 data-dpr="1" 时写的尺寸,而这时我们使用的flexible引入时的 data-dpr不是一个写死了的,是一个动态的;会导致组件样式变小。解决方法:使用 post-px2rem-exclude 让flexible不编译第三方库的文件(忽略ui组件库的样式文件)

    // 安装
    npm  install postcss-px2rem-exclude --save
    
    // 配置。配置在项目根目录的 postcss.config.js 文件,如果你的项目没有生成这个独立文件,就需要在你的 package.json 里设置。
    
    >>>> postcss.config.js 文件中的配置方式
    
        module.exports = {
          plugins: {
            autoprefixer: {},
            "postcss-px2rem-exclude": {
              remUnit: 75, // 这是rem适配的配置。注意:remUnit在这里要根据lib-flexible的规则来配制,如果您的设计稿是750px的,用75就刚刚好。
              exclude: /node_modules|folder_name/i
            }
          }
        };

    >>>> package.json 文件中配置方式
    
        "postcss": {
        "plugins": {
          "autoprefixer": {},
          "postcss-px2rem-exclude":{
              "remUnit": 75,
              "exclude":"/node_modules|floder_name/i"
          }
        }
      },