背景
通过配置webpack,实现px自动转成vw,实现移动端的自适应
做法
执行以下命令安装依赖:
千万注意千万注意千万注意要指定版本,否则会报错,提示依赖需要postcss8以上版本的支持
npm i postcss-import@12.0.1 postcss-url@9.0.0 cssnano@3.10.0 postcss-aspect-ratio-mini@0.0.2 postcss-cssnext@3.1.0 postcss-px-to-viewport@0.0.3 postcss-viewport-units@0.1.6 postcss-write-svg@3.0.1 -S
接着项目根目录新增.postcssrc.js文件
module.exports = { "plugins": { "postcss-import": {}, "postcss-url": {}, "postcss-aspect-ratio-mini": {}, "postcss-write-svg": { utf8: false }, "postcss-cssnext": {}, "postcss-px-to-viewport": { viewportWidth: 750, // (Number) The width of the viewport. viewportHeight: 1334, // (Number) The height of the viewport. unitPrecision: 3, // (Number) The decimal numbers to allow the REM units to grow to. viewportUnit: 'vw', // (String) Expected units. selectorBlackList: ['.ignore', '.hairlines'], // (Array) The selectors to ignore and leave as px. minPixelValue: 1, // (Number) Set the minimum pixel value to replace. mediaQuery: false // (Boolean) Allow px to be converted in media queries. }, "postcss-viewport-units":{ filterRule: rule => rule.selector.includes('::after') && rule.selector.includes('::before') && rule.selector.includes(':after') && rule.selector.includes(':before') }, "cssnano": { preset: "advanced", autoprefixer: false, "postcss-zindex": false } } }
之后修改项目文件.browserslistrc,千万注意去掉“not dead”,否则会提示Error: Loading PostCSS Plugin failed: Unknown browser query dead
.browserslistrc
> 1% last 2 versions
最后,运行项目,当样式写px时,则会自动转为vw,自适应配置成功。
参考
https://www.jianshu.com/p/ae0623fac11e
https://blog.csdn.net/liyunkun888/article/details/91868776
https://www.jianshu.com/p/bd9cb7861b85
https://blog.csdn.net/qq_39241544/article/details/105968832