UNPKG

t-comm

Version:

专业、稳定、纯粹的工具库

55 lines (51 loc) 1.71 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); /** * PostCSS 插件:将 rpx 单位转换为 px * * 基于 750 设计稿,1rpx = 0.5px。 * 内置平台判断,默认仅在 h5 平台执行。 * * @param {object} options - 配置选项 * @param {number} options.ratio - rpx 到 px 的转换比例,默认 0.5 * @param {string[]} options.platform - 在哪些平台执行,默认 ['h5'] * * @example * * ```js * // postcss.config.js * const { rpxToPxPlugin } = require('t-comm'); * * module.exports = { * plugins: [ * // 默认仅在 h5 平台执行,无需外部判断 * rpxToPxPlugin(), * // 自定义比例和平台 * rpxToPxPlugin({ ratio: 1, platform: ['h5', 'mp-weixin'] }), * ], * }; * ``` */ var rpxToPxPlugin = function rpxToPxPlugin() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var _options$ratio = options.ratio, ratio = _options$ratio === void 0 ? 0.5 : _options$ratio, _options$platform = options.platform, platform = _options$platform === void 0 ? ['h5'] : _options$platform; var currentPlatform = process.env.UNI_PLATFORM || ''; var shouldRun = platform.includes(currentPlatform); return { postcssPlugin: 'postcss-rpx-to-px', Declaration: function Declaration(decl) { if (!shouldRun) return; if (decl.value.includes('rpx')) { decl.value = decl.value.replace(/(\d*\.?\d+)rpx/gi, function (match, num) { return "".concat((parseFloat(num) * ratio).toFixed(2).replace(/\.?0+$/, ''), "px"); }); } } }; }; // PostCSS 插件标识 rpxToPxPlugin.postcss = true; exports.rpxToPxPlugin = rpxToPxPlugin;