前端适配方案之 flexible.js 到 postcss-px-to-viewport-8-plugin插件演进
响应式布局从页面表现来说,就是根据浏览器的大小变化而变化。
以前经常使用 amfe-flexible.js 这个库,再通过IDE的cssrem插件转换视觉稿单位 px => rem。
amfe-flexible官方也提示大家使用,viewport来替代。
也许有同学使用postcss-px-to-viewport 这个插件,是的。他是postcss-px-to-viewport-8-plugin 插件的前身。
使用 postcss-px-to-viewport 控制台报以下代码
postcss-px-to-viewport: postcss.plugin was deprecated. Migration guide: https://evilmartians.com/chronicles/postcss-8-plugin-migration
解决
postcss-px-to-viewport 替换 postcss-px-to-viewport-8-plugin 修复因为postcss版本导致的atRule is not a constructor 问题。
postcss-px-to-view-port-8-plugin 依赖其它三方库版本如下:
"postcss": "^8.3.8", // 8.0.0版本都不会转单位"postcss-loader": "^6.1.1",
笔者使用的架构是 vite+react
postcss.config.js 配置
export default {plugins: {'postcss-px-to-viewport-8-plugin': {unitToConvert: 'px', // 需要转换的单位,默认为"px"viewportWidth: 1920, // 设计稿的视口宽度unitPrecision: 5, // 单位转换后保留的精度propList: ['*'], // 需要转换的 CSS 属性列表, 例如['*']代表全部,['html']表示仅对html有效viewportUnit: 'vw', // 转换后的视口单位fontViewportUnit: 'vw', // 转换后的字体单位selectorBlackList: ['.ignore', '.hairlines'], // 不进行转换的 CSS 类名minPixelValue: 1, // 设置转换的最小像素值(3px会被转换为1vw)mediaQuery: false, // 媒体查询里的单位是否需要转换单位},autoprefixer: {},},
}
注意:viewportWidth – 设计稿的视口宽度,这个是设计稿的大小。
更多配置请参考:https://github.com/krmao/postcss-px-to-viewport-8-plugin
代码
// jsxfunction App() {return (<><div className="header-box"><div className="header-title">【1303室】</div><div className="header-rcn"><div className="c1">安全第一责任人:李帅彬</div><div className="c2"><div className="time">20:20</div><div className="date">2025-04-29</div><div className="week">星期一</div></div></div></div></>);
}export default App;// css代码
.header-box {height: 188px;background-color: #2003b0;padding: 0 70px;color: #fff;display: flex;align-items: center;justify-content: space-between;
}.header-title {font-size: 92px;font-weight: 500;
}.header-rcn {display: inline-flex;align-items: flex-end;
}.header-rcn .c1 {color: #d4f802;font-size: 38px;padding: 0 0 20px 0;
}.header-rcn .c2 {margin-left: 40px;text-align: center;
}.header-rcn .c2 .time {font-size: 40px;
}.header-rcn .c2 .date {font-size: 30px;
}.header-rcn .c2 .week {font-size: 30px;
}
预览
更多实践