amfe-flexible同时适应pc端和移动端方法
使用背景同一个框架下面需要开发PC端和移动端,框架目录如下:调用amfe-flexible实现了移动端自适应,但是在PC端想实现因为vue.config.js的rootValue只能设置一个,所以PC端自适应会因为移动端的rootValue页面组件变的巨大无比。require('postcss-pxtorem')({ // 把px单位换算成rem单位rootValue: 37.5, // 换算的基
使用背景
同一个框架下面需要开发PC端和移动端,框架目录如下:
调用amfe-flexible实现了移动端自适应,但是在PC端想实现因为vue.config.js的rootValue只能设置一个,所以PC端自适应会因为移动端的rootValue页面组件变的巨大无比。
require('postcss-pxtorem')({ // 把px单位换算成rem单位
rootValue: 37.5, // 换算的基数(设计图750的根字体为75)
// selectorBlackList: ['.van-'], // 忽略转换正则匹配项
propList: ['*']
})
现在需要一个能自动根据移动端和PC端调用不同rootValue的解决方案。
修改vue.config.js文件
先在vue.config.js文件里面把PC端的rootValue添加进去,这里设置了一个rootValue=192来设置PC端的值
require('postcss-pxtorem')({ // 把px单位换算成rem单位
rootValue: 37.5, // 换算的基数(设计图750的根字体为75)
rootValuePC: 192,
// selectorBlackList: ['.van-'], // 忽略转换正则匹配项
propList: ['*']
})
修改postcss-pxtorem\index.js文件
文件地址:D:\work\H5\splc-web\node_modules\postcss-pxtorem\index.js
来读下源码
module.exports = postcss.plugin("postcss-pxtorem", options => {
..................
})
options用来接收vue.config.js传递过来的属性,其中就有我们前面设置的rootValuePC
return css => {
const exclude = opts.exclude;
const filePath = css.source.input.file;
if (
exclude &&
((type.isFunction(exclude) && exclude(filePath)) ||
(type.isString(exclude) && filePath.indexOf(exclude) !== -1) ||
filePath.match(exclude) !== null)
) {
return;
}
const rootValue =
typeof opts.rootValue === "function"
? opts.rootValue(css.source.input)
: opts.rootValue;
const pxReplace = createPxReplace(
rootValue,
opts.unitPrecision,
opts.minPixelValue
);
..............................
上面代码filePath为项目里面的文件路径,postcss已经对文件类型等进行了判断处理,从const rootValue这行开始就是需要转换的px值文件路径
let rootValue =
typeof opts.rootValue === "function"
? opts.rootValue(css.source.input)
: opts.rootValue;
//自定义如果是element-ui或者是views\pc页面则使用pcRootValue
if (filePath.indexOf("\\node_modules\\vxe-table") > -1 || filePath.indexOf("\\node_modules\\element-ui") > -1 || filePath.indexOf("\\src\\views\\pc") > -1) {
rootValue = opts.rootValuePC;
console.log(" pc client adapting:", rootValue + " | " + filePath);
}
最终代码修改如果下:
const rootValue 改成 let
新增一个判断,把PC端的前端组件库elemnt-ui和views下的pc端文件做个判断,然后给rootValue复制我们从vue.config.js传递过来的rootValuePC
项目运行的时候可以看到相关文件已经根据需求调用了不同的rootvalue
附上相关依赖
“amfe-flexible”: “^2.2.1”,
“postcss-pxtorem”: “^5.1.1”,
-----------------------------------------UPDATE-----------------------------------------
2020年11月23日更新
顶部defaults配置里面的minPixelValue为最小转换值,既小于2px的元素一概不转换rem
const defaults = {
rootValue: 16,
unitPrecision: 5,
selectorBlackList: [],
propList: ["font", "font-size", "line-height", "letter-spacing"],
replace: true,
mediaQuery: false,
minPixelValue: 2,
exclude: null
};
更多推荐
所有评论(0)