環(huán)境信息:
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.在項(xiàng)目根目錄創(chuàng)建一個(gè)config-overrides.js 文件
3.安裝 postcss-plugin-px2rem 和 lib-flexible (注意這里安裝 postcss-px2rem、px2rem這類都行,都是 px2rem衍生的庫(kù),不過(guò)不同的庫(kù)具體配置不一樣,建議查看文檔具體有哪些參數(shù)。查看方法可以去 npm 官網(wǎng) 搜索包名,查看詳情即可,或者問(wèn) 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’; )
5.public/index.html 里 注釋調(diào) meta 和加上 一段兼容ipad和ipad pro 的兼容代碼。
注釋掉(注釋的原因是 lib-flexible 會(huì)自動(dòng)創(chuàng)建 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>
這段代碼用于檢測(cè)用戶是否正在使用iPhone、iPad、iPod或iOS等蘋果設(shè)備。如果是,它將創(chuàng)建一個(gè)新的視口元標(biāo)簽,并添加到HTML文檔的頭部。視口元標(biāo)簽的內(nèi)容設(shè)置為 ‘target-densitydpi=device-dpi, width=480px, user-scalable=no’,這意味著它會(huì)嘗試讓頁(yè)面在各種設(shè)備上看起來(lái)相似,頁(yè)面的寬度被設(shè)置為480px,并且用戶不能手動(dòng)縮放頁(yè)面。
我的 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" />
<meta
name="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 a
user'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" will
work 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>
6.重新運(yùn)行 npm start 審查元素 看看 px 是不是被轉(zhuǎn)換成了rem。如果轉(zhuǎn)換成功說(shuō)明,配置成功了。
可以在 App.js 里加上一個(gè)div然后在 App.css 里寫上一個(gè)width,height然后 用到 div上。
.box{
width: 100px;
height: 100px;
background: red;
}
運(yùn)行之后的效果截圖:
從100px轉(zhuǎn)換成了1.333rem ,當(dāng)切換時(shí),他也跟著變大變小。
rootValue 的計(jì)算方式 :
rootValue=設(shè)計(jì)圖的寬度/10
我是 375*812的設(shè)計(jì)圖 所以 就是 375/10=37.5
計(jì)算rem值時(shí),應(yīng)該將屏幕寬度除以10作為基準(zhǔn)值。
postcss-plugin-px2rem 詳細(xì)配置:
postcss-plugin-px2rem是一個(gè)PostCSS插件,用于將px單位轉(zhuǎn)換為rem單位。該插件提供了以下參數(shù):
rootValue:指定根元素字體大小的值,默認(rèn)為16。該值用于將px轉(zhuǎn)換為rem,例如,當(dāng)rootValue設(shè)置為16時(shí),10px會(huì)被轉(zhuǎn)換為0.625rem。
unitPrecision:指定轉(zhuǎn)換后的rem值保留的小數(shù)位數(shù),默認(rèn)為5。
propList:指定需要轉(zhuǎn)換的CSS屬性,默認(rèn)為[‘*’],表示所有屬性都會(huì)被轉(zhuǎn)換。你可以將其設(shè)為只轉(zhuǎn)換某些屬性,例如[‘font-size’]只轉(zhuǎn)換字體大小屬性。
selectorBlackList:指定不需要轉(zhuǎn)換的選擇器,可以是字符串或正則表達(dá)式。例如,你可以將其設(shè)置為[‘.no-rem’]來(lái)防止某些元素被轉(zhuǎn)換。
replace:指定是否替換原始的px值,默認(rèn)為true。如果設(shè)置為false,則會(huì)在原始值后面添加轉(zhuǎn)換后的rem值,例如10px會(huì)被轉(zhuǎn)換為10px /* 0.625rem */。
mediaQuery:指定是否在媒體查詢中也進(jìn)行轉(zhuǎn)換,默認(rèn)為false。
minPixelValue:指定最小轉(zhuǎn)換單位的px值,默認(rèn)為0。如果設(shè)置為2,則不會(huì)將1px轉(zhuǎn)換為0.0625rem等非常小的值。
以下是一個(gè)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
})
]
};
在上述示例中,我們將根元素的字體大小設(shè)置為16,保留5位小數(shù),只轉(zhuǎn)換除font-size以外的所有屬性,不轉(zhuǎn)換帶有.no-rem類名的元素,替換原始的px值,不在媒體查詢中進(jìn)行轉(zhuǎn)換,最小轉(zhuǎn)換單位的px值為0。
完整的配置代碼:
addWebpackAlias和 addLessLoader 你可以忽略。前者是 別名 src 可以寫成@ ,后者是 可以使用less 語(yǔ)法。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-726959.html
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"),
})
);
總結(jié):
我是根據(jù) issues里的回答寫出來(lái)的具體可參考:
react項(xiàng)目:在configoveride.js中addPostcssPlugins添加postcss-pxtorem無(wú)效
其他配置可以參考:
react create-react-app v5 從零搭建項(xiàng)目(不暴露 eject)文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-726959.html
到了這里,關(guān)于react create-react-app v5配置 px2rem (不暴露 eject方式)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!