UNPKG

postcss-rem2px-yuze

Version:

Convert rem units to px or rpx units using PostCSS (JavaScript version with include feature)

117 lines (103 loc) 2.88 kB
const { remRegex } = require('./regex') const { postcssPlugin, getConfig, createRemReplace, declarationExists, blacklistedSelector, createPropListMatcher, createExcludeMatcher, createIncludeMatcher, } = require('./shared') /** * PostCSS rem转响应式像素插件 * @param {object} options 配置选项 * @returns {object} PostCSS插件对象 */ function postcssRemToResponsivePixel(options = {}) { const config = getConfig(options) const { exclude, include, mediaQuery, minRemValue, propList, replace, rootValue, selectorBlackList, transformUnit, unitPrecision, disabled, } = config // 如果插件被禁用,返回空插件 if (disabled) { return { postcssPlugin, } } const satisfyPropList = createPropListMatcher(propList) const excludeFn = createExcludeMatcher(exclude) const includeFn = createIncludeMatcher(include) return { postcssPlugin, Once(css) { const source = css.source const input = source && source.input const filePath = input && input.file // 文件路径过滤 const isExcludeFile = excludeFn(filePath) const isIncludeFile = includeFn(filePath) // 如果文件被排除或者不在包含列表中,则跳过处理 if (isExcludeFile || !isIncludeFile) { return } // 计算根字体大小 const _rootValue = typeof rootValue === 'function' ? rootValue(input) : rootValue // 创建rem替换函数console.log('isExcludeFile',filePath,isExcludeFile,isIncludeFile) const pxReplace = createRemReplace( _rootValue, unitPrecision, minRemValue, transformUnit ) // 处理CSS声明 css.walkDecls((decl) => { const rule = decl.parent // 检查是否需要处理 if ( !decl.value.includes('rem') || !satisfyPropList(decl.prop) || blacklistedSelector(selectorBlackList, rule.selector) ) { return } // 替换rem单位 const value = decl.value.replace(remRegex, pxReplace) // 检查是否已存在相同声明 if (declarationExists(rule, decl.prop, value)) { return } // 替换或添加新声明 if (replace) { decl.value = value } else { decl.cloneAfter({ value }) } }) // 处理媒体查询 if (mediaQuery) { css.walkAtRules((atRule) => { if (atRule.name === 'media') { if (!atRule.params.includes('rem')) { return } atRule.params = atRule.params.replace(remRegex, pxReplace) } }) } }, } } // 设置PostCSS插件标识 postcssRemToResponsivePixel.postcss = true module.exports = postcssRemToResponsivePixel