首先先安装amfe-flexible跟postcss-pxtorem依赖,postcss-pxtorem依赖是4.0.1版本的。
接下来修改vue.config.js文件
require('postcss-pxtorem')({ // 把px单位换算成rem单位
rootValue: 37.5, // 换算的基数(设计图750的根字体为75)
rootValuePC: 192,
// selectorBlackList: ['.van-'], // 忽略转换正则匹配项
propList: ['*']
})
修改postcss-pxtorem\index.js文件
文件地址在node_modules\postcss-pxtorem\index.js
修改顶部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
};
接下来修改这里面的方法
module.exports = postcss.plugin('postcss-pxtorem', function (options) {
})
module.exports = postcss.plugin('postcss-pxtorem', function (options) {
convertLegacyOptions(options);
var opts = objectAssign({}, defaults, options);
var satisfyPropList = createPropListMatcher(opts.propList);
return function (css) {
const filePath = css.source.input.file;
css.walkDecls(function (decl, i) {
// This should be the fastest test and will remove most declarations
if (decl.value.indexOf('px') === -1) return;
if (!satisfyPropList(decl.prop)) return;
if (blacklistedSelector(opts.selectorBlackList, decl.parent.selector)) return;
const filePath = css.source.input.file;
let 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;
}else{
rootValue = opts.rootValue
}
var pxReplace = createPxReplace(rootValue, opts.unitPrecision, opts.minPixelValue);
var value = decl.value.replace(pxRegex, pxReplace);
// if rem unit already exists, do not add or replace
if (declarationExists(decl.parent, decl.prop, value)) return;
if (opts.replace) {
decl.value = value;
} else {
decl.parent.insertAfter(i, decl.clone({ value: value }));
}
});
if (opts.mediaQuery) {
css.walkAtRules('media', function (rule) {
if (rule.params.indexOf('px') === -1) return;
rule.params = rule.params.replace(pxRegex, pxReplace);
});
}
};
});
接下来就完成了。