首先安装sass sass-loader
我用的是node16版本,安装sass@1.69.5 sass-loader@13.3.2
如果安装报错请找对应你node版本的sass和sass-loader
以下适配代码写在静态样式scss文件中,
<style lang="scss">
@use "sass:math";
$defaultWidth: 1920;
$defaultHeight: 1080;
@function vw($px) {
@return math.div($px, $defaultWidth) * 100vw;
}
@function vh($px) {
@return math.div($px, $defaultHeight) * 100vh;
}
.box {
width: vw(200);
height: vh(200);
background: blue;
}
</style>
math.div接收两个参数,1除数,2被除数,math还有其他方法,类似js中Math的方法,具体用法请看官方文档Sass: sass:math
报错的话math.div报错的话可能是scss版本不支持,直接使用除号
通过下面方式配置confid.js
css: {
loaderOptions: {
scss: {
additionalData(content, loaderContext) {
const { resourcePath, rootContext } = loaderContext
const relativePath = path.relative(rootContext, resourcePath)
if (relativePath.replace(/\\/g, '/') !== 'src/assets/styles/default.scss') {
return `@import "~@/assets/styles/default.scss";${content}`
}
return content
}
}
}
},