less-px转rem插件

22次阅读

共计 1490 个字符,预计需要花费 4 分钟才能阅读完成。

由于开发移动端页面,做 ui 设配,使用 less 作为 css 预编译语言,由于或者自己才疏学浅,没有找到现成关于 lesspx 转 rem 的插件,或者对 less 语法不太够熟练,采用这种极端的写法,
特此开发:
…………………………….
不知道是自己脑残,还是咋的,看 less 文档对插件的写法,发现不好使,最终只能看 less 部分源码,和
某些 less 插件的写法,借此作为借鉴。
……………………………..
以下为代码:
文件名 pxToRem.js

function Pxtorem(options = {}) {
  const defaultOptions = {
    basePx: options.basePx || 37.5,// 设计稿 跨度 /10
    precision: options.precision || false, // px 转成 rem 后的数字精度
  }
  this.options = Object.assign({}, defaultOptions, options);
}
Pxtorem.prototype.install = function (less, pluginsmannager, functionRegistry) {
  const that = this;
  functionRegistry.addMultiple({pxToRem(pxObject, precisionObject) {
      const {
        options: {basePx,},
      } = that;
      let {
        options: {precision,},
      } = that;
      const {value: px,} = pxObject;
      precisionObject && (precision = precisionObject.value);
      let rem = px / basePx;
      if (precision !== false && typeof precision === 'number') {rem = rem.toFixed(precision);
      }
      return `${rem}rem`;
    },
  });
};
// 数字精度转换
function controlPrecision (number, precision) {const numberStr = String(number);
  const numList = numberStr.split('.');
  const lastNumStr = numList[1];
  if ((lastNumStr && lastNumStr.length === 0) || (numberStr.length <= precision)) {return numberStr;}
  if (numberStr.length > precision) {const precisionLastNextBit = numberStr[precision];
    const num = Number(precisionLastNextBit);
    let outNumber = Number(numberStr.substr(0, precision));
    num >= 5 && (outNumber++);
    return outNumber;
  }
}
module.exports = Pxtorem

使用方法在 webpack 里配置

const PxToRem = require('./pxToRem');
...
{
    loader: 'less-loader',
    options: {
      plugins: [PxToRem,],
  }
...

less 中使用

.container {width: pxToRem(37.5px);
}

会转成

.container {width: 1rem;}

正文完
 0