react 项目中css样式px自动转vw,适配移动端和pc端。修改下配置项里面的viewportWidth和viewportHeight
移动端一般配置:(一般根据苹果6-7-8尺寸:750*1334px)
{//..."viewportWidth": "750", // 视窗的宽度,对应的是我们设计稿的宽度"viewportHeight": "1334", // 视窗的高度}
PC端一般配置:(一般1080P主流:1920*1080px)
{//..."viewportWidth": "1920", // 视窗的宽度,对应的是我们设计稿的宽度"viewportHeight": "1080", // 视窗的高度}
【1】安装
安装:postcss-px-to-viewport 和 postcss-loader
//1.npm方式:npm install postcss-loader postcss-px-to-viewport --save-dev//2.yarn安装:yarn add -D postcss-loader postcss-px-to-viewport
二:暴露项目配置项(任选一种)
注意:此步骤不可逆,最好备份下项目再进行。
若报错,有git的可以通过 git add .git commit -m '暴露项目配置项'npm run eject
npm方式:npm run ejectcnpm方式:cnpm run ejectyarn方式:yarn eject
【3】配置 webpack.config.js
文件内搜索(100行左右位置):const getStyleLoaders = (cssOptions,
查看webpack配置代码版本,这里有两种版本样式,配置稍有点区别
1.若结构是这样的,使用该配置方式
postcss-px-to-viewport其他 配置项,看本文最后的补充
['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: [], // (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.}],
2.若长这样:
postcss-px-to-viewport其他 配置项,看本文最后的补充
require('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: [], // (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-px-to-viewport配置项
{unitToConvert: "px",// 要转化的单位viewportWidth: 750,// UI设计稿的宽度viewportHeight: 1334, // UI设计稿的高度unitPrecision: 3,// 转换后的精度,即小数点位数propList: ["*"],// 指定转换的css属性的单位,*代表全部css属性的单位都进行转换viewportUnit: "vw",// 指定需要转换成的视窗单位,默认vwfontViewportUnit: "vw",// 指定字体需要转换成的视窗单位,默认vwlandscapeUnit: 'vh',// 横屏时使用的单位landscapeWidth: 667,// 横屏时使用的视口宽度selectorBlackList: [],// 指定不转换为视窗单位的类名minPixelValue: 1,// 默认值1,小于或等于1px则不进行转换mediaQuery: false,// 是否在媒体查询的css代码中也进行转换,默认falsereplace: true,// 是否转换后直接更换属性值// landscape: false, // 是否处理横屏情况exclude: /(\/|\\)(node_modules)(\/|\\)/, // 设置忽略文件,用正则做目录名匹配}