Install lib-flexible, postcss-pxtorem
1 yarn add lib- flexible 2 yarn add postcss-pxtorem
Configure postcss-pxtorem
Create a postcss.config.js file in the root directory
1 const pxtorem = require("postcss-pxtorem" ); 2 module.exports = { 3 plugins: [ 4 pxtorem({ 5 rootValue: 136, // What I configure here is my benchmark value at 1366 resolution, which will be The following explains 6 unitPrecision: 5 , 7 propList: ["*" ], 8 selectorBlackList: [/^\.nop2r/, /^\.am/,'html' ], 9 // Exclude antd style, because I give html Min-width is set, so html is also excluded and rem conversion is not performed 10 replace: true , 11 mediaQuery: false , 12 minPixelValue: 0 13 }) 14 ] 15 }
Configure lib-flexible
Under normal circumstances, we can import’lib-flexible’ in app.js, but I started the project after the introduction, and kept reporting window is not defined. After studying for a long time, I found a solution.
1 const setRem = async ()=> { 2 await require('lib-flexible' ) 3 } 4 useEffect(()=> { 5 setRem() 6 window.addEventListener('resize' ,setRem) 7 })
Finally no errors were reported!
In this case, it is no problem to adapt to the mobile terminal, but in the case of the PC terminal screen, use the console to view the elements and find that the font-size is always 54px
1 <html data-dpr="1" style="font-size: 54px;">
Solution:
Modify the refreshRem of node_modules\lib-flexible\flexible.js file. It can be seen that the original code does not change with width when width / dpr> 540. We modify this code as follows:
1 function refreshRem(){ 2 var width = docEl.getBoundingClientRect().width; 3 if (width / dpr> 540 ) { 4 width = width * dpr; 5 } 6 var rem = width / 10 ; 7 docEl.style. fontSize = rem +'px' ; 8 flexible.rem = win.rem = rem; 9 }
at last
According to the design drawing and the resolution under development, modify the rootValue value of the postcss-pxtorem.js file, the normal resolution is width/10