flexible
是手淘开发的移动端适配的框架,核心原理是根据屏幕宽度不同,给html根节点设置不同的font-size,项目中所有的px单位改成rem就能实现在不同的设备中实现页面适配。
postcss-pxtorem
是一款自动将项目中css文件中的px转为rem的npm插件。
安装插件
npm i lib-flexible px2rem-loader --save
安装完成后在根目录index.js中引入lib-flexible
:
import 'lib-flexible'
使用npm eject
命令暴露出所有配置,这一步要慎重,因为配置一旦暴露出来就不能恢复了。
命令执行之前需要先提交git,执行完成后在根目录中会出现config文件夹:
下一步打开编辑webpack.config.js文件,在其中添加px替换rpx规则:
{
// Options for PostCSS as we reference these options twice
// Adds vendor prefixing based on your specified browser support in
// package.json
loader: require.resolve('postcss-loader'),
options: {
postcssOptions: {
ident: 'postcss',
config: false,
plugins: !useTailwind
? [
'postcss-flexbugs-fixes',
[
'postcss-preset-env',
{
autoprefixer: {
flexbox: 'no-2009'
},
stage: 3
}
],
// 插入内容start
[
'postcss-pxtorem',
{
rootValue: 75, //设计图最大宽度除以10 //比如750的宽就写成75
selectorBlackList: ['test-'],
propList: ['*'],
exclude: /node_modules/i
}
],
// 插入内容end
'postcss-normalize'
]
: [
'tailwindcss',
'postcss-flexbugs-fixes',
[
'postcss-preset-env',
{
autoprefixer: {
flexbox: 'no-2009'
},
stage: 3
}
],
// 插入内容start
[
'postcss-pxtorem',
{
rootValue: 75, //设计图最大宽度除以10 //比如750的宽就写成75
selectorBlackList: ['test-'],
propList: ['*'],
exclude: /node_modules/i
}
],
// 插入内容end
},
sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment
}
},
配置完成之后项目需要重新运行才会生效。
未使用适配和使用适配之后效果对比
css部分代码:
.red {
font-size: 20px;
width: 700px;
height: 70px;
}
.icon {
height: 70px;
}
.red {
background-color: red;
}
/* 不转换为rem的样式 */
.test-red {
font-size: 20px;
width: 700px;
height: 70px;
}
.test-icon {
height: 70px;
}
.test-red {
background-color: red;
}
JavaScript部分代码:
import './App.css'
function App() {
return (
<>
<div>使用postcss-px2rem转换前:</div>
<div className="test-red">
<img className="test-icon" src="./logo192.png" alt="" />
</div>
<div>使用postcss-px2rem转换后:</div>
<div className="red">
<img className="icon" src="./logo192.png" alt="" />
</div>
</>
)
}
export default App
多个尺寸显示效果对比: