最近在开发vue3 + vite + ts + view-ui-plus的库,使用了Less 4.2.0来写样式,并定制了view-ui-plus的样式:
变量覆盖#
如果你的项目使用了 webpack/vite 工程,可以通过变量覆盖的方式来实现主题定制。
首先在项目中先建立一个 less 文件 viewUITheme.less,并写入下面内容:
@import '~view-ui-plus/src/styles/index.less'; // Here are the variables to cover, such as: @primary-color: #8c0776;
完整的变量列表可以查看 默认样式变量。
然后在入口文件
main.js
内导入这个 less 文件即可:import './viewUITheme.less';
然后在使用一些组件时,发现样式出现了异常:
左边是异常的,右边是正常的,经过排查,是因为出现了一个无效样式:
正是这个高度没有被浏览器识别成功,导致图标没出显示出来,翻阅Less官方文档,发现以下描述:
Math
Released v3.7.0
lessc -m=[option]
lessc --math=[option]
{ math: '[option]' }
Less has re-built math options to offer an in-between feature between the previous
strictMath
setting, which required parentheses all the time, and the default, which performed math in all situations.In order to cause fewer conflicts with CSS, which now liberally uses the
/
symbol between values, there is now a math mode that only requires parentheses for division. (This is now the default in Less 4.) "Strict math" has also been tweaked to operate more intuitively, although the legacy behavior is supported.The four options available for
math
are:
always
(3.x default) - Less does math eagerlyparens-division
(4.0 default) - No division is performed outside of parens using/
operator (but can be "forced" outside of parens with./
operator -./
is deprecated)parens
|strict
- Parens required for all math expressions.strict-legacy
(removed in 4.0) - In some cases, math will not be evaluated if any part of the expression cannot be evaluated.always Example:
.math { a: 1 + 1; b: 2px / 2; c: 2px ./ 2; d: (2px / 2); }
Outputs:
.math { a: 2; b: 1px; c: 1px; d: 1px; }
parens-division
Example:
.math { a: 1 + 1; b: 2px / 2; c: 2px ./ 2; d: (2px / 2); }
Outputs:
.math { a: 2; b: 2px / 2; c: 1px; d: 1px; }
大致意思就是,关于math的一些配置在不同less版本有所区别,less4.0以上版本,像 2px / 2 这种样式值,会直接被应用到浏览器上,而less3会被计算成1px然后应用到浏览器,less4默认是parens-division,less3默认是always。而view-ui-plus用的是less2,也是always配置。
所以,要简单解决这个问题,在vite.config.ts里把less的math设置成always模式就行了:
export default defineConfig({
css: {
preprocessorOptions: {
less: {
javascriptEnabled: true,
rewriteUrls: 'all',
math: 'always' //就是这里设置math模式
}
}
},
})