react 項目中css樣式px自動轉vw,適配移動端和pc端。修改下配置項里面的viewportWidth和viewportHeigh
- 安裝: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 eject
cnpm方式:
cnpm run eject
yarn方式:
yarn eject
- 【3】配置 webpack.config.js
- 文件內搜索(100行左右位置):const getStyleLoaders = (cssOptions,
- 查看webpack配置代碼版本,這里有兩種版本樣式,配置稍有點區別
-
若結構是這樣的,使用該配置方式
image
-
[
'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.其他的方式:
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.
}),
-
最后效果
img