下载依赖

由于 vue-cli 脚手架一直再更新,包括 webpack 及相关依赖都在升级,下面代码仅供参考
本人目前使用 @vue/cli 4.5.9, 下面是依赖包的版本号

1
2
3
4
cnpm install postcss
cnpm install postcss-loader
cnpm install postcss-pxtorem
cnpm install autoprefix

方式一:vue.config.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const pxtorem = require("postcss-pxtorem");
module.exports = {
css: {
loaderOptions: {
postcss: {
plugins: [
pxtorem({
rootValue: 16, // 根字体大小,如果设计图是750的话 记得除2
unitPrecision: 5,
propList: ["*"], // 作用在哪些属性上 我这里用的是通配符
selectorBlackList: ["vant-"], // 将哪些html元素排除在外,我这里添加了一个vant的
replace: true,
mediaQuery: false,
minPixelValue: 12,
exclude: /node_modules/i,
}),
],
},
},
},
};

方式二:项目根目录添加.postcssrc.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
module.exports = {
plugins: {
autoprefixer: {},
"postcss-pxtorem": {
rootValue: 16, // 根字体大小,如果设计图是750的话 记得除2
unitPrecision: 5,
propList: ["*"], // 作用在哪些属性上 我这里用的是通配符
selectorBlackList: ["vant-"], // 将哪些html元素排除在外,我这里添加了一个vant的
replace: true,
mediaQuery: false,
minPixelValue: 12,
exclude: /node_modules/i,
},
},
};

浏览器兼容前缀

方式一:
项目根目录创建 vue.config.js

1
2
3
4
5
6
7
{
"browserslist": [
"defaults",
"not ie <= 8",
"chrome >= 14"
]
}

项目根目录创建.postcssrc.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const autoprefixer = require("autoprefixer");

module.exports = {
css: {
loaderOptions: {
postcss: {
plugins: [
// 自动添加兼容css前缀
autoprefixer(),
],
},
},
},
};

方式二:项目根目录添加.postcssrc.js

  1. 项目根目录创建 .browserslistrc
1
2
3
defaults
not ie <= 8
chrome >= 14
  1. 项目根目录创建.postcssrc.js
1
2
3
4
5
module.exports = {
plugins: {
autoprefixer: {},
},
};

动态设置根节点 html 的 fontSize

可以再 main.js 中直接引入下面的脚本

1
2
3
4
5
6
7
8
9
10
11
12
(function () {
const baseSize = 16; // 32
function setRem() {
const scale = document.documentElement.clientWidth / 375; // 750
document.documentElement.style.fontSize =
baseSize * Math.min(scale, 2) + "px";
}

window.onresize = function () {
setRem();
};
})();