1.下载依赖文件
npm i -S amfe-flexible
npm install postcss-pxtorem --save-dev
2.安装后,在main.js
中引入amfe-flexible
import 'amfe-flexible'
3.接着在项目根目录新建一个postcss.config.js
文件
Vue3脚手架项目
|-public
|-src
|-postcss.config.js
4.postcss.config.js
文件内容,根据设计稿大小选择
/**
* 这一段代码,设计稿的宽度是750
*/
module.exports = {
plugins: {
"postcss-pxtorem": {
rootValue({ file }) {
return file.indexOf("vant") !== -1 ? 37.5 : 75;
},
propList: ["*"], // 需要转换的css属性,默认*全部
},
},
};
/**
* 这一段代码,设计稿的宽度是1080
*/
module.exports = {
plugins: {
"postcss-pxtorem": {
rootValue({ file }) {
return file.indexOf("vant") !== -1 ? 108 : 216; // 设计稿宽度为1080px,基准值分别为108和216
},
propList: ["*"], // 需要转换的css属性,这里设置为全部
},
},
};
5.避坑指南
项目是cli,那么新建postcss.config.js就可以,如果是vite项目,文件名尾缀必须是(.cjs)postcss.config.cjs,否则会出现vite项目中无法将px转换成rem的情况