# mixin 方案
@default-w: 375px;
.convert(@px, @width: @default-w) {
@var: unit(@px / @width) * 10;
@rem: ~'@{var}rem';
}
# 使用
.el-mixin {
width: .convert(300px)[@rem];
height: .convert(150px)[@rem];
background: red;
}
# @function 方案
Webpack中对less-loader设置javascriptEnabled,使其支持编写Javascript
{
test: /\.less/,
exclude: /node_modules/,
use: ['style-loader', 'css-loader', {
loader: 'less-loader',
options: {
javascriptEnabled: true
}
}],
}
编写函数
.remMixin() {
@functions: ~`(function() {
var clientWidth = '375px';
function convert(size) {
return typeof size === 'string' ?
+size.replace('px', '') : size;
}
this.rem = function(size) {
return convert(size) / convert(clientWidth) * 10 + 'rem';
}
})()`;
}
.remMixin();
# 使用
.el-function {
width: ~`rem("300px")`;
height: ~`rem(150)`;
background: blue;
}
文件参考:https://juejin.cn/post/6844903841251459080 (opens new window)