react create-react-app v5配置 px2rem (不暴露 eject方式)

2023-10-09 22:12

本文主要是介绍react create-react-app v5配置 px2rem (不暴露 eject方式),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

环境信息:

create-react-app v5
“react”: “^18.2.0”
“postcss-plugin-px2rem”: “^0.8.1”

配置步骤:

不暴露 eject 配置自己的webpack:
1.下载react-app-rewired 和 customize-cra-5

npm install react-app-rewired customize-cra-5 --save-dev

2.在项目根目录创建一个config-overrides.js 文件

3.安装 postcss-plugin-px2rem 和 lib-flexible (注意这里安装 postcss-px2rem、px2rem这类都行,都是 px2rem衍生的库,不过不同的库具体配置不一样,建议查看文档具体有哪些参数。查看方法可以去 npm 官网 搜索包名,查看详情即可,或者问 ai 比如: 文心,gpt)

cnpm install postcss-plugin-px2rem  lib-flexible --save

4.配置config/webpack.config.js

加上这段代码重写addPostcssPlugins 方法:

// 重写 addPostcssPlugins 方法
const addPostcssPlugins = plugins => (config) => {const rules = config.module.rules.find(rule => Array.isArray(rule.oneOf)).oneOf;rules.forEach(r => r.use&& r.use.forEach((u) => {if (u.options && u.options.postcssOptions && u.options.postcssOptions.ident === 'postcss') {if (!u.options.postcssOptions.plugins) {u.options.postcssOptions.plugins = plugins;}if (u.options.postcssOptions.plugins) {const originalPlugins = u.options.postcssOptions.plugins;u.options.postcssOptions.plugins = [originalPlugins, ...plugins];}}}));return config;
};

然后 使用配置:

addPostcssPlugins([['postcss-pxtorem', {rootValue: 37.5,propList: ['*'],}]]),

或者 :

 addPostcssPlugins([['postcss-px2rem-exclude', {remUnit: 37.5,exclude: /node_modules/i,}]]),

4.在 src/index.js(入口文件引入 import ‘lib-flexible’; )
入口文件引入 import 'lib-flexible';
5.public/index.html 里 注释调 meta 和加上 一段兼容ipad和ipad pro 的兼容代码。

注释掉(注释的原因是 lib-flexible 会自动创建 meta):

<meta name="viewport" content="width=device-width, initial-scale=1" />

在 head里加上(ipad和ipad pro ):

<!-- 淘宝弹性布局方案lib-flexible不兼容ipad和ipad pro的解决方法 --><script>/(iPhone|iPad|iPhone OS|Phone|iPod|iOS)/i.test(navigator.userAgent)&&(head=document.getElementsByTagName('head'),viewport=document.createElement('meta'),viewport.name='viewport',viewport.content='target-densitydpi=device-dpi, width=480px, user-scalable=no',head.length>0&&head[head.length-1].appendChild(viewport));</script>

这段代码用于检测用户是否正在使用iPhone、iPad、iPod或iOS等苹果设备。如果是,它将创建一个新的视口元标签,并添加到HTML文档的头部。视口元标签的内容设置为 ‘target-densitydpi=device-dpi, width=480px, user-scalable=no’,这意味着它会尝试让页面在各种设备上看起来相似,页面的宽度被设置为480px,并且用户不能手动缩放页面。

我的 index.html 代码如下:

<!DOCTYPE html>
<html lang="en"><head><meta charset="utf-8" /><link rel="icon" href="%PUBLIC_URL%/favicon.ico" /><!-- <meta name="viewport" content="width=device-width, initial-scale=1" /> --><meta name="theme-color" content="#000000" /><metaname="description"content="Web site created using create-react-app"/><link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" /><!--manifest.json provides metadata used when your web app is installed on auser's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/--><link rel="manifest" href="%PUBLIC_URL%/manifest.json" /><!--Notice the use of %PUBLIC_URL% in the tags above.It will be replaced with the URL of the `public` folder during the build.Only files inside the `public` folder can be referenced from the HTML.Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" willwork correctly both with client-side routing and a non-root public URL.Learn how to configure a non-root public URL by running `npm run build`.--><title>React App</title><!-- 淘宝弹性布局方案lib-flexible不兼容ipad和ipad pro的解决方法 --><script>/(iPhone|iPad|iPhone OS|Phone|iPod|iOS)/i.test(navigator.userAgent)&&(head=document.getElementsByTagName('head'),viewport=document.createElement('meta'),viewport.name='viewport',viewport.content='target-densitydpi=device-dpi, width=480px, user-scalable=no',head.length>0&&head[head.length-1].appendChild(viewport));</script></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div><!--This HTML file is a template.If you open it directly in the browser, you will see an empty page.You can add webfonts, meta tags, or analytics to this file.The build step will place the bundled scripts into the <body> tag.To begin the development, run `npm start` or `yarn start`.To create a production bundle, use `npm run build` or `yarn build`.--></body></html>

index.html截图
6.重新运行 npm start 审查元素 看看 px 是不是被转换成了rem。如果转换成功说明,配置成功了。
可以在 App.js 里加上一个div然后在 App.css 里写上一个width,height然后 用到 div上。

.box{width: 100px;height: 100px;background: red;
}

测试代码
运行之后的效果截图:
从100px转换成了1.333rem ,当切换时,他也跟着变大变小。
运行后的效果截图

完整的配置代码:

addWebpackAlias和 addLessLoader 你可以忽略。前者是 别名 src 可以写成@ ,后者是 可以使用less 语法。

const {override,addLessLoader,// addPostcssPlugins,fixBabelImports,addWebpackAlias,
} = require("customize-cra-5");
const path = require("path");
// 重写 addPostcssPlugins 方法
const addPostcssPlugins = plugins => (config) => {const rules = config.module.rules.find(rule => Array.isArray(rule.oneOf)).oneOf;rules.forEach(r => r.use&& r.use.forEach((u) => {if (u.options && u.options.postcssOptions && u.options.postcssOptions.ident === 'postcss') {if (!u.options.postcssOptions.plugins) {u.options.postcssOptions.plugins = plugins;}if (u.options.postcssOptions.plugins) {const originalPlugins = u.options.postcssOptions.plugins;u.options.postcssOptions.plugins = [originalPlugins, ...plugins];}}}));return config;
};module.exports = override(addLessLoader({lessOptions: {javascriptEnabled: true,// modifyVars: { '@primary-color': '#1DA57A' }, // 你的主题色},}),addPostcssPlugins([['postcss-pxtorem', {rootValue: 37.5,propList: ['*'],}]]),// addPostcssPlugins([['postcss-px2rem-exclude', {//   remUnit: 37.5,//   exclude: /node_modules/i,// }]]),addWebpackAlias({"@": path.resolve("src"),})
);

总结:

我是根据 issues里的回答写出来的具体可参考:
react项目:在configoveride.js中addPostcssPlugins添加postcss-pxtorem无效
github ieeues 截图
其他配置可以参考:
react create-react-app v5 从零搭建项目(不暴露 eject)

这篇关于react create-react-app v5配置 px2rem (不暴露 eject方式)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/175920

相关文章

gradle第三方Jar包依赖统一管理方式

《gradle第三方Jar包依赖统一管理方式》:本文主要介绍gradle第三方Jar包依赖统一管理方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录背景实现1.顶层模块build.gradle添加依赖管理插件2.顶层模块build.gradle添加所有管理依赖包

Linux之systemV共享内存方式

《Linux之systemV共享内存方式》:本文主要介绍Linux之systemV共享内存方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、工作原理二、系统调用接口1、申请共享内存(一)key的获取(二)共享内存的申请2、将共享内存段连接到进程地址空间3、将

Maven中引入 springboot 相关依赖的方式(最新推荐)

《Maven中引入springboot相关依赖的方式(最新推荐)》:本文主要介绍Maven中引入springboot相关依赖的方式(最新推荐),本文给大家介绍的非常详细,对大家的学习或工作具有... 目录Maven中引入 springboot 相关依赖的方式1. 不使用版本管理(不推荐)2、使用版本管理(推

SpringBoot3.4配置校验新特性的用法详解

《SpringBoot3.4配置校验新特性的用法详解》SpringBoot3.4对配置校验支持进行了全面升级,这篇文章为大家详细介绍了一下它们的具体使用,文中的示例代码讲解详细,感兴趣的小伙伴可以参考... 目录基本用法示例定义配置类配置 application.yml注入使用嵌套对象与集合元素深度校验开发

C#使用StackExchange.Redis实现分布式锁的两种方式介绍

《C#使用StackExchange.Redis实现分布式锁的两种方式介绍》分布式锁在集群的架构中发挥着重要的作用,:本文主要介绍C#使用StackExchange.Redis实现分布式锁的... 目录自定义分布式锁获取锁释放锁自动续期StackExchange.Redis分布式锁获取锁释放锁自动续期分布式

IntelliJ IDEA 中配置 Spring MVC 环境的详细步骤及问题解决

《IntelliJIDEA中配置SpringMVC环境的详细步骤及问题解决》:本文主要介绍IntelliJIDEA中配置SpringMVC环境的详细步骤及问题解决,本文分步骤结合实例给大... 目录步骤 1:创建 Maven Web 项目步骤 2:添加 Spring MVC 依赖1、保存后执行2、将新的依赖

Java对象转换的实现方式汇总

《Java对象转换的实现方式汇总》:本文主要介绍Java对象转换的多种实现方式,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录Java对象转换的多种实现方式1. 手动映射(Manual Mapping)2. Builder模式3. 工具类辅助映

SpringBoot基于配置实现短信服务策略的动态切换

《SpringBoot基于配置实现短信服务策略的动态切换》这篇文章主要为大家详细介绍了SpringBoot在接入多个短信服务商(如阿里云、腾讯云、华为云)后,如何根据配置或环境切换使用不同的服务商,需... 目录目标功能示例配置(application.yml)配置类绑定短信发送策略接口示例:阿里云 & 腾

Spring Boot读取配置文件的五种方式小结

《SpringBoot读取配置文件的五种方式小结》SpringBoot提供了灵活多样的方式来读取配置文件,这篇文章为大家介绍了5种常见的读取方式,文中的示例代码简洁易懂,大家可以根据自己的需要进... 目录1. 配置文件位置与加载顺序2. 读取配置文件的方式汇总方式一:使用 @Value 注解读取配置方式二

如何为Yarn配置国内源的详细教程

《如何为Yarn配置国内源的详细教程》在使用Yarn进行项目开发时,由于网络原因,直接使用官方源可能会导致下载速度慢或连接失败,配置国内源可以显著提高包的下载速度和稳定性,本文将详细介绍如何为Yarn... 目录一、查询当前使用的镜像源二、设置国内源1. 设置为淘宝镜像源2. 设置为其他国内源三、还原为官方