postcss-pxtorem 是一款 postcss 插件,用于将 px 单位转化为 rem
lib-flexible 用于设置 rem 基准值
1 安装依赖
yarn add amfe-flexible
或者使用
npm i amfe-flexible
然后在main.js中加载执行该模块
import 'amfe-flexible'
2安装postcss-pxtorem依赖:
yarn add -D postcss-pxtorem
或者是
npm install postcss-pxtorem -D
这里解释一下:# -D 是 --save-dev 的简写 把依赖包的版本信息写进 package.json 文件里面
3 在vue-cli中使用 然后在项目根目录中创建 postcss.config.js 文件:
module.exports = {
plugins: {
// postcss-pxtorem 插件的版本需要 >= 5.0.0
// 适用版本 5.1.1
// yarn add -D postcss-pxtorem@5.1.1
// npm install postcss-pxtorem@5.1.1 -D
'postcss-pxtorem': {
rootValue({ file }) { // 判断是否是vant的文件 如果是就使用 37.5为根节点字体大小
// 否则使用75 因为vant使用的设计标准为375 但是市场现在的主流设置尺寸是750
return file.indexOf('vant') !== -1 ? 37.5 : 75;
},
// 配置哪些文件中的尺寸需要转化为rem *表示所有的都要转化
propList: ['*'],
},
},
};
这个文件会被自执行
4 在vite中使用,在vite.config.js中配置postcss-pxtorem
import postCssPxToRem from "postcss-pxtorem"
...
export default defineConfig({
...
css: {
postcss: {
plugins: [
postCssPxToRem({
rootValue: 37.5, // 1rem的大小
propList: ['*'], // 需要转换的属性,这里选择全部都进行转换
})
]
}
},
...
})