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

2023-10-11 02:15

本文主要是介绍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 ,当切换时,他也跟着变大变小。
运行后的效果截图

rootValue 的计算方式 :

rootValue=设计图的宽度/10
我是 375*812的设计图 所以 就是 375/10=37.5
计算rem值时,应该将屏幕宽度除以10作为基准值。

postcss-plugin-px2rem 详细配置:

postcss-plugin-px2rem是一个PostCSS插件,用于将px单位转换为rem单位。该插件提供了以下参数:

rootValue:指定根元素字体大小的值,默认为16。该值用于将px转换为rem,例如,当rootValue设置为16时,10px会被转换为0.625rem。

unitPrecision:指定转换后的rem值保留的小数位数,默认为5。

propList:指定需要转换的CSS属性,默认为[‘*’],表示所有属性都会被转换。你可以将其设为只转换某些属性,例如[‘font-size’]只转换字体大小属性。

selectorBlackList:指定不需要转换的选择器,可以是字符串或正则表达式。例如,你可以将其设置为[‘.no-rem’]来防止某些元素被转换。

replace:指定是否替换原始的px值,默认为true。如果设置为false,则会在原始值后面添加转换后的rem值,例如10px会被转换为10px /* 0.625rem */。

mediaQuery:指定是否在媒体查询中也进行转换,默认为false。

minPixelValue:指定最小转换单位的px值,默认为0。如果设置为2,则不会将1px转换为0.0625rem等非常小的值。

以下是一个postcss-plugin-px2rem插件的配置示例:

const px2rem = require('postcss-plugin-px2rem');
const postcssOptions = {plugins: [px2rem({rootValue: 16,unitPrecision: 5,propList: ['*', '!font-size'],selectorBlackList: ['.no-rem'],replace: true,mediaQuery: false,minPixelValue: 0})]
};

在上述示例中,我们将根元素的字体大小设置为16,保留5位小数,只转换除font-size以外的所有属性,不转换带有.no-rem类名的元素,替换原始的px值,不在媒体查询中进行转换,最小转换单位的px值为0。

完整的配置代码:

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/184802

相关文章

Linux线程之线程的创建、属性、回收、退出、取消方式

《Linux线程之线程的创建、属性、回收、退出、取消方式》文章总结了线程管理核心知识:线程号唯一、创建方式、属性设置(如分离状态与栈大小)、回收机制(join/detach)、退出方法(返回/pthr... 目录1. 线程号2. 线程的创建3. 线程属性4. 线程的回收5. 线程的退出6. 线程的取消7.

Linux下进程的CPU配置与线程绑定过程

《Linux下进程的CPU配置与线程绑定过程》本文介绍Linux系统中基于进程和线程的CPU配置方法,通过taskset命令和pthread库调整亲和力,将进程/线程绑定到特定CPU核心以优化资源分配... 目录1 基于进程的CPU配置1.1 对CPU亲和力的配置1.2 绑定进程到指定CPU核上运行2 基于

golang程序打包成脚本部署到Linux系统方式

《golang程序打包成脚本部署到Linux系统方式》Golang程序通过本地编译(设置GOOS为linux生成无后缀二进制文件),上传至Linux服务器后赋权执行,使用nohup命令实现后台运行,完... 目录本地编译golang程序上传Golang二进制文件到linux服务器总结本地编译Golang程序

Linux下删除乱码文件和目录的实现方式

《Linux下删除乱码文件和目录的实现方式》:本文主要介绍Linux下删除乱码文件和目录的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录linux下删除乱码文件和目录方法1方法2总结Linux下删除乱码文件和目录方法1使用ls -i命令找到文件或目录

Spring Boot spring-boot-maven-plugin 参数配置详解(最新推荐)

《SpringBootspring-boot-maven-plugin参数配置详解(最新推荐)》文章介绍了SpringBootMaven插件的5个核心目标(repackage、run、start... 目录一 spring-boot-maven-plugin 插件的5个Goals二 应用场景1 重新打包应用

Linux在线解压jar包的实现方式

《Linux在线解压jar包的实现方式》:本文主要介绍Linux在线解压jar包的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录linux在线解压jar包解压 jar包的步骤总结Linux在线解压jar包在 Centos 中解压 jar 包可以使用 u

Java中读取YAML文件配置信息常见问题及解决方法

《Java中读取YAML文件配置信息常见问题及解决方法》:本文主要介绍Java中读取YAML文件配置信息常见问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 目录1 使用Spring Boot的@ConfigurationProperties2. 使用@Valu

Jenkins分布式集群配置方式

《Jenkins分布式集群配置方式》:本文主要介绍Jenkins分布式集群配置方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1.安装jenkins2.配置集群总结Jenkins是一个开源项目,它提供了一个容易使用的持续集成系统,并且提供了大量的plugin满

Java通过驱动包(jar包)连接MySQL数据库的步骤总结及验证方式

《Java通过驱动包(jar包)连接MySQL数据库的步骤总结及验证方式》本文详细介绍如何使用Java通过JDBC连接MySQL数据库,包括下载驱动、配置Eclipse环境、检测数据库连接等关键步骤,... 目录一、下载驱动包二、放jar包三、检测数据库连接JavaJava 如何使用 JDBC 连接 mys

SpringBoot线程池配置使用示例详解

《SpringBoot线程池配置使用示例详解》SpringBoot集成@Async注解,支持线程池参数配置(核心数、队列容量、拒绝策略等)及生命周期管理,结合监控与任务装饰器,提升异步处理效率与系统... 目录一、核心特性二、添加依赖三、参数详解四、配置线程池五、应用实践代码说明拒绝策略(Rejected