css: {
loaderOptions: {
postcss: {
plugins: (params) => {
console.log(params.context);
console.log(params.resourcePath);
let path = params.context;
console.log(path);
if (/layouts/.test(path)) { //pc路径
return [
require("postcss-px-to-viewport")({
unitToConvert: "px", // 默认值`px`,需要转换的单位
viewportWidth: 1200, // 视窗的宽度,对应设计稿宽度
viewportHeight: 1316, // 视窗的高度, 根据375设备的宽度来指定,一般是667,也可不配置
unitPrecision: 3, // 指定`px`转换为视窗单位值的小数位数
propList: ["*"], // 转化为vw的属性列表
viewportUnit: "vw", // 指定需要转换成视窗单位
fontViewportUnit: "vw", // 字体使用的视窗单位
selectorBlaskList: [".ignore-"], // 指定不需要转换为视窗单位的类
mediaQuery: true, // 允许在媒体查询中转换`px`
minPixelValue: 2, // 小于或等于`1px`时不转换为视窗单位
replace: true, // 是否直接更换属性值而不添加备用属性
exclude: [/node_modules/, /layoutmobile/], // 忽略某些文件夹下的文件或特定文件
landscape: false, // 是否添加根据landscapeWidth生成的媒体查询条件 @media (orientation: landscape)
landscapeUnit: "vw", // 横屏时使用的单位
landscapeWidth: 1200, // 横屏时使用的视窗宽度
}),
];
} else if (/layoutmobile/.test(path)) { //h5路径
return [
require("postcss-px-to-viewport")({
unitToConvert: "px", // 默认值`px`,需要转换的单位
viewportWidth: 750, // 视窗的宽度,对应设计稿宽度
viewportHeight: 1334, // 视窗的高度, 根据375设备的宽度来指定,一般是667,也可不配置
unitPrecision: 3, // 指定`px`转换为视窗单位值的小数位数
propList: ["*"], // 转化为vw的属性列表
viewportUnit: "vw", // 指定需要转换成视窗单位
fontViewportUnit: "vw", // 字体使用的视窗单位
selectorBlaskList: [".ignore-"], // 指定不需要转换为视窗单位的类
mediaQuery: true, // 允许在媒体查询中转换`px`
minPixelValue: 2, // 小于或等于`1px`时不转换为视窗单位
replace: true, // 是否直接更换属性值而不添加备用属性
exclude: [/node_modules/, /layouts/], // 忽略某些文件夹下的文件或特定文件
landscape: false, // 是否添加根据landscapeWidth生成的媒体查询条件 @media (orientation: landscape)
landscapeUnit: "vw", // 横屏时使用的单位
landscapeWidth: 1080, // 横屏时使用的视窗宽度
}),
];
} else {
return [];
}
},
},
},
},
module.exports = {
plugins: [
require('postcss-px-to-viewport')({
..., // other options
viewportWidth: 375, // 移动端视窗高度 -> 375
exclude: [/node_modules/, /view-desktop/], // 忽略 node_modules 和 桌面端组件
}),
require('postcss-px-to-viewport')({
..., // other options
viewportWidth: 1920, // 桌面端视窗的宽度 -> 1920
exclude: [/node_modules/, /view-mobile/], // 忽略 node_modules 和 移动端组件
}),
],
}
P.S. 环境:vite@v3.2.1
Originally posted by @hopo-o in #75