React移动端适配

一、安装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.
              },
            ],
          ],
        },
      },
    },
  },

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值