vue cli怎么实现rem
Vue CLI 实现 rem 适配方案
在 Vue CLI 项目中实现 rem 适配,通常需要结合 postcss-pxtorem 插件和动态设置根字体大小。以下是具体实现步骤:
安装 postcss-pxtorem
通过 npm 或 yarn 安装 postcss 插件:
npm install postcss-pxtorem -D
# 或
yarn add postcss-pxtorem -D
配置 postcss.config.js
在项目根目录创建或修改 postcss.config.js 文件:
module.exports = {
plugins: {
'postcss-pxtorem': {
rootValue: 16, // 基准值,1rem = 16px
propList: ['*'], // 转换所有属性
selectorBlackList: [/^html$/], // 排除 html 标签
},
},
};
动态设置根字体大小
在 src/utils 目录下创建 rem.js 文件:
// 基准大小
const baseSize = 16;
function setRem() {
const scale = document.documentElement.clientWidth / 1920; // 设计稿宽度
document.documentElement.style.fontSize = `${baseSize * Math.min(scale, 2)}px`;
}
// 初始化
setRem();
// 窗口变化时重置
window.onresize = function() {
setRem();
};
在 main.js 中引入
在项目入口文件 src/main.js 中引入 rem 设置:
import './utils/rem';
可选:使用 lib-flexible
作为替代方案,可以安装 amfe-flexible 自动处理适配:
npm install amfe-flexible -S
然后在 main.js 中引入:
import 'amfe-flexible';
注意事项
- 设计稿测量值需直接填写像素值,插件会自动转换为 rem
- 对于不想转换的样式,可通过
PX单位绕过转换 - 移动端项目建议将
rootValue设置为设计稿宽度/10(如750设计稿设为75)
以上方案实现了:
- 开发时直接使用设计稿像素值
- 自动转换为 rem 单位
- 根据屏幕宽度动态调整根字体大小
- 完美适配各种屏幕尺寸







