2023年了,还在手动px转rem吗?

176 阅读1分钟

px-to-rem

使用amfe-flexible和postcss-pxtorem在webpack中配置px转rem

npm i amfe-flexible -S

npm i postcss-pxtorem -D

在main.js中

import flexible from 'amfe-flexible' 
Vue.use(flexible);

index.html中

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">

vue.config.js 或 webpack.config.js

module.exports = {	
	css: {
		loaderOptions: {
			postcss: {
				plugins: [
					require('postcss-pxtorem')({ // 把px单位换算成rem单位
						rootValue: 192.0,//rootValue根据设计稿宽度除以10进行设置,这边假设设计稿为1920,即rootValue设为192.0;
						unitPrecision: 5,
						propList: ['*'],
						// selectorBlackList: ['el-',], //
						replace: true,
						mediaQuery: false,
						minPixelValue: 0
					})
				]
			}
		}
	}
};

px-to-vw

使用postcss-px-to-viewport插件

  1. 在项目根目录下添加.postcssrc.js文件
module.exports = {
  plugins: {
    autoprefixer: {}, // 用来给不同的浏览器自动添加相应前缀,如-webkit-,-moz-等等
    "postcss-px-to-viewport": {
      unitToConvert: "px", // 要转化的单位
      viewportWidth: 750, // UI设计稿的宽度
      unitPrecision: 6, // 转换后的精度,即小数点位数
      propList: ["*"], // 指定转换的css属性的单位,*代表全部css属性的单位都进行转换
      viewportUnit: "vw", // 指定需要转换成的视窗单位,默认vw
      fontViewportUnit: "vw", // 指定字体需要转换成的视窗单位,默认vw
      selectorBlackList: ["wrap"], // 指定不转换为视窗单位的类名,
      minPixelValue: 1, // 默认值1,小于或等于1px则不进行转换
      mediaQuery: true, // 是否在媒体查询的css代码中也进行转换,默认false
      replace: true, // 是否转换后直接更换属性值
      exclude: [/node_modules/], // 设置忽略文件,用正则做目录名匹配
      landscape: false // 是否处理横屏情况
    }
  }
};