@wuipkg/postcss-pxtorem
v0.2.3
Published
PostCSS plugin that converts px units to rem units with per-file state isolation.
Maintainers
Readme
@wuipkg/postcss-pxtorem
将 CSS 声明中的 px 转为 rem 的 PostCSS 插件。
本包基于 postcss-pxtorem 源码整理,并改为由 wuipkg 工作区统一构建和发布。上游仓库的 GitHub Actions、Husky、旧 Jasmine 测试及其他仓库级文件未纳入本包。
与上游的关键差异
[email protected] 会将当前文件的换算函数缓存到插件实例中。Vite 并发处理多个 CSS 文件时会复用同一插件实例;如果 rootValue 根据文件名返回不同基准,后处理的文件可能覆盖先处理文件的换算基准。
本包在 PostCSS prepare() 钩子中为每次 CSS 处理创建独立的状态闭包。因此 Vant、@wuipkg/component 使用 37.5(375 设计稿基准)、业务样式使用 75(750 设计稿基准)等按文件区分基准的场景可以并发构建,不会相互串扰。
新包只支持当前的 camelCase 配置名,例如 rootValue、propList;不保留上游已废弃的 snake_case 与 propWhiteList 别名。
安装
pnpm add -D postcss @wuipkg/postcss-pxtoremVite 使用方式
import autoprefixer from 'autoprefixer'
import { defineConfig } from 'vite'
import postcssPxToRem from '@wuipkg/postcss-pxtorem'
export default defineConfig({
css: {
postcss: {
plugins: [
postcssPxToRem({
minPixelValue: 2,
rootValue: ({ file }) => {
if (file?.includes('vant')) return 37.5
if (file?.includes('@wuipkg/component')) return 37.5
return 75
},
propList: ['*']
}),
autoprefixer()
]
}
}
})例如业务 CSS 中的 width: 750px 会按 75 输出为 10rem;Vant、@wuipkg/component CSS 中同样的值会按 37.5 输出为 20rem。即使多份样式并发处理,结果也保持稳定。
配置项
| 配置 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| rootValue | number \| (input) => number | 16 | 根字号基准。函数接收 PostCSS Input,可按文件路径返回不同基准。 |
| unitPrecision | number | 5 | rem 小数精度。 |
| propList | string[] | 字体相关属性 | 允许转换的 CSS 属性;['*'] 表示全部属性,! 前缀表示排除。 |
| selectorBlackList | (string \| RegExp)[] | [] | 命中的选择器保持原单位。 |
| replace | boolean | true | false 时保留原 px 声明并追加 rem 声明。 |
| mediaQuery | boolean | false | 是否转换 @media 参数中的单位。 |
| minPixelValue | number | 0 | 小于该值的 px 不转换。 |
| exclude | string \| RegExp \| (filePath) => boolean | null | 命中的 CSS 文件不转换。 |
| unit | string | 'px' | 要转换的单位。 |
构建与测试
本包使用 Vite library mode 输出 ESM、CommonJS 与类型声明:
pnpm --filter @wuipkg/postcss-pxtorem test
pnpm --filter @wuipkg/postcss-pxtorem build测试包含 Vite 风格的异步并发场景,验证按文件返回不同 rootValue 时不会发生状态串扰。
