在react中使用postcss-px-to-viewport

之前写过一篇文章在vue项目中使用postcss-px-to-viewport,现在更新一下在react项目中使用postcss-px-to-viewport的方式.

新建 react 项目

npx

1
npx create-react-app my-app

npm

1
npm init react-app my-app

yarn

1
2
3
4
yarn create react-app my-app

# 使用typescript模板
yarn create react-app my-app --template typescript

安装 postcss-px-to-viewport

1
yarn add postcss-px-to-viewport

暴露 webpack config

yarn

1
yarn eject

需要注意的是,在eject之前,需要执行git 的提交操作.

1
2
git add .
git commit -m "init"

修改 /config/webpack.config.js

1
2
3
4
5
6
7
8
9
require("postcss-px-to-viewport")({
viewportWidth: 1920, // (Number) The width of the viewport.
viewportHeight: 1080, // (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配置可以看下官方文档https://github.com/evrone/postcss-px-to-viewport/blob/master/README_CN.md

img

在 postcss-loader 的 plugins 插入即可.

thank u !