react使用插件postcss-pxtorem
配置px自动转换rem
1.下载postcss-pxtorem
插件
| npm install postcss postcss-pxtorem --save-dev |
2.下载craco ,进行webpack的配置(ant design中的),或者在webpack.config.js中,这里的话我使用antd的craco插件
3.在项目根目录创建一个craco.config.js
进行配置
| const pxtorem = require("postcss-pxtorem"); |
| |
| module.exports = { |
| style: { |
| postcss: { |
| plugins: [ |
| pxtorem({ |
| rootValue: 3.75, |
| unitPrecision: 5, |
| propList: [ |
| "font", |
| "font-size", |
| "line-height", |
| "letter-spacing", |
| "width", |
| "height", |
| ], |
| selectorBlackList: [], |
| replace: true, |
| mediaQuery: false, |
| minPixelValue: 0, |
| exclude: /node_modules/i, |
| }), |
| ], |
| }, |
| }, |
| }; |
| |
4.如果报错:Error: PostCSS plugin postcss-pxtorem requires PostCSS 8
,因为postcss-pxtorem
最高也才6.0.0版本(就2021年5月31日来说是6.0.0,往后就不知道了),只需下载指定5.1.1版本的postcss-pxtorem
就行了
| npm install postcss-pxtorem@5.1.1 --save-dev |
5.到这里其实还会遇到一个bug,就是元素转换的rem对了,但是展示的效果却不一样,这是因为我们没有设置根标签默认的字体大小,这里有一个根据不同设备会设置根标签的默认字体大小,只要引进你的react入口文件就好了,拿走不谢
| (function flexible (window, document) { |
| var docEl = document.documentElement |
| var dpr = window.devicePixelRatio || 1 |
| |
| |
| function setBodyFontSize () { |
| if (document.body) { |
| document.body.style.fontSize = '16px' |
| } else { |
| |
| |
| |
| |
| document.addEventListener('DOMContentLoaded', setBodyFontSize) |
| } |
| } |
| setBodyFontSize(); |
| |
| |
| function setRemUnit () { |
| var rem = docEl.clientWidth / 100 |
| docEl.style.fontSize = rem + 'px' |
| } |
| |
| setRemUnit() |
| |
| |
| window.addEventListener('resize', setRemUnit) |
| window.addEventListener('pageshow', function (e) { |
| if (e.persisted) { |
| setRemUnit() |
| } |
| }) |
| |
| |
| if (dpr >= 2) { |
| var fakeBody = document.createElement('body') |
| var testElement = document.createElement('div') |
| testElement.style.border = '.5px solid transparent' |
| fakeBody.appendChild(testElement) |
| docEl.appendChild(fakeBody) |
| if (testElement.offsetHeight === 1) { |
| docEl.classList.add('hairlines') |
| } |
| docEl.removeChild(fakeBody) |
| } |
| }(window, document)) |
| |
如上步骤进行配置就不用自己对px进行rem转换了,按照设计稿来就ok了
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· DeepSeek 解答了困扰我五年的技术问题
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库