一、安装craco (用来覆盖React脚手架中webpack的配置项)
npm i -D @craco/craco
二、安装 lib_flexible(用于根据屏幕的尺寸改变根元素的font-size大小->屏幕宽度/10)
npm i lib-flexible
三、安装postcss的插件 postcss-pxtorem (用于在框架中自动将px转化为rem)
npm i postcss-pxtorem
四、在项目根目录中创建craco.config.js
module.exports = {
style: {
postcss: {
mode: "extends",
loaderOptions: {
postcssOptions: {
ident: "postcss",
plugins: [
[
"postcss-pxtorem",
{
rootValue: 375 / 10, // 根元素字体大小
propList: ["*"],
exclude: /node_modules/i,
},
],
],
},
},
},
},
};
五、在package.json 修改启动脚本
"scripts": {
"start": "react-scripts start"
"start": "craco start"
"build": "react-scripts build"
"build": "craco build"
"test": "react-scripts test"
"test": "craco test"
}
六、在入口文件中导入 lib-flexible
import "lib-flexible/flexible";
配置pxtoviewport
配置方式和上面内容基本一致区别在于使用的postcss插件变为了postcss-px-to-viewport
npm i postcss-px-to-viewport
注意使用viewport单位就不要再下载lib-flexible
style: {
postcss: {
mode: "extends",
loaderOptions: {
postcssOptions: {
ident: "postcss",
plugins: [
[
"postcss-px-to-viewport",
{
viewportWidth: 375, // (Number) The width of the viewport.
viewportHeight: 667, // (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.
},
],
],
},
},
},
},
1007






