vue项目中引入less的全局变量

项目根目录执行命令

1
vue add style-resources-loader

vue.config.js

1
2
3
4
5
6
7
8
9
10
11
const path = require('path');
module.exports = {
pluginOptions: {
'style-resources-loader': {
preProcessor: 'less',
patterns: [
path.resolve(__dirname, './src/assets/styles/variables.less'),
path.resolve(__dirname, './src/assets/styles/global.less')]
}
}
}

variables.less

1
2
3
4
5
@primary-color: #ffa500;
@info-color: #b5f5ec;
@success-color: #52c41a;
@error-color: #ffbb96;
@warning-color:#bae7ff;

global.less

1
2
3
4
5
6
.primary-bg {
background-color: @primary-color;
}
.success-bg {
background-color: @success-color;
}

页面使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png" />
<h2>less 全局变量引入</h2>
<ul>
<li><span class="primary">primary color</span></li>
<li><span class="info">info color</span></li>
<li><span class="success">success color</span></li>
<li><span class="error">error color</span></li>
</ul>
<h2>less 全局类名引入</h2>
<ul>
<li><span class="primary-bg">primary-bg</span></li>
<li><span class="success-bg">success-bg</span></li>
</ul>
</div>
</template>

<script>
export default {
name: "App",
components: {},
};
</script>

<style lang="less" scope>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
font-size: 50px;
.primary {
color: @primary-color;
}
.info {
color: @info-color;
}
.success {
color: @success-color;
}
.error {
color: @error-color;
}
.warning {
color: @warning-color;
}
}
</style>

效果图