UNPKG

postcss-rem2px-yuze

Version:

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

184 lines (149 loc) 3.69 kB
# postcss-rem-to-responsive-pixel (JavaScript版本) 一个用于将CSS中的rem单位转换为px或rpx单位的PostCSS插件,支持include/exclude功能。 ## 特性 - ✅ 将rem单位转换为px或rpx单位 - ✅ 支持include功能:指定需要处理的文件或文件夹 - ✅ 支持exclude功能:排除不需要处理的文件 - ✅ 支持小程序rpx单位 - ✅ 灵活的配置选项 - ✅ 媒体查询支持 - ✅ 选择器黑名单 - ✅ 属性白名单 ## 安装 ```bash npm install postcss-rem-to-responsive-pixel-js --save-dev ``` ## 使用方法 ### 基础用法 ```js // postcss.config.js module.exports = { plugins: [ require('postcss-rem-to-responsive-pixel-js')({ rootValue: 16, propList: ['*'], transformUnit: 'px', }), ], } ``` ### 小程序开发 ```js // postcss.config.js module.exports = { plugins: [ require('tailwindcss'), require('postcss-rem-to-responsive-pixel-js')({ rootValue: 32, propList: ['*'], transformUnit: 'rpx', include: ['src/**/*.css', 'src/**/*.scss'], exclude: [/node_modules/], }), ], } ``` ## 配置选项 ```js const defaultOptions = { rootValue: 16, // 根字体大小 unitPrecision: 5, // 数值精度 selectorBlackList: [], // 选择器黑名单 propList: ['font', 'font-size', 'line-height', 'letter-spacing'], // 处理的属性 replace: true, // 是否替换原值 mediaQuery: false, // 是否处理媒体查询 minRemValue: 0, // 最小转换值 exclude: [/node_modules/i], // 排除文件 include: [], // 包含文件(新功能) transformUnit: 'px', // 输出单位 'px' | 'rpx' disabled: false, // 是否禁用 } ``` ### include选项详解 `include`选项支持多种格式: #### 1. 字符串数组(文件路径匹配) ```js { include: ['src/components', 'src/pages', 'index.css'] } ``` #### 2. 正则表达式数组 ```js { include: [/\.css$/, /\.scss$/, /components/] } ``` #### 3. 函数 ```js { include: (filePath) => { return filePath.includes('components') || filePath.endsWith('.module.css') } } ``` #### 4. 混合使用 ```js { include: ['src/components', /\.module\.css$/, (path) => path.includes('theme')] } ``` ### exclude优先级 当同时设置`include`和`exclude`时,`exclude`具有更高的优先级: ```js { include: ['src/**/*.css'], exclude: ['src/vendor/**/*.css'] // 这些文件不会被处理 } ``` ## 使用示例 ### 输入 ```css h1 { margin: 0 0 20px; font-size: 2rem; line-height: 1.2; letter-spacing: 0.0625rem; } ``` ### 输出(transformUnit: 'px') ```css h1 { margin: 0 0 20px; font-size: 32px; line-height: 1.2; letter-spacing: 1px; } ``` ### 输出(transformUnit: 'rpx') ```css h1 { margin: 0 0 20px; font-size: 32rpx; line-height: 1.2; letter-spacing: 1rpx; } ``` ## 忽略转换 使用大写的`REM`或`Rem`可以忽略转换: ```css .ignore { font-size: 1REM; /* 不会被转换 */ margin: 2rem; /* 会被转换 */ } ``` ## 文件结构 ``` ├── index.js # 主入口文件 ├── shared.js # 共享工具函数 ├── defaults.js # 默认配置 ├── regex.js # 正则表达式 └── README.md # 使用说明 ``` ## API ### 主要函数 - `postcssRemToResponsivePixel(options)` - 创建插件实例 - `getConfig(options)` - 合并配置选项 - `createIncludeMatcher(include)` - 创建文件包含匹配器 - `createExcludeMatcher(exclude)` - 创建文件排除匹配器 ## 许可证 MIT