This guide assumes you have initialized a project using the Vue CLI scaffolding with Vite support:
npm init vue@latest
Ensure your dependencies align with modern versions, such as:
"@vitejs/plugin-vue": "^5.0.4",
"vue": "^3.4.21"
Objective
The goal is to configure the project sothat global LESS variables defined in a central file are automatically available in every Vue Single File Component (SFC) without requiring manual imports in each file.
Common Pitfalls
Many traditional solutions suggest modifying vue.config.js or installing packages like style-resources-loader. These approaches are specific to Webpack-based Vue CLI projects. Since this project utilizes Vite as the build tool, those configurations will not take effect.
Implementation Steps
1. Install LESS
Vite has built-in support for pre-processors, but you still need to install LESS as a development dependency. Note that less-loader is not required for Vite projects.
npm install -D less
2. Verify Basic Usage
Once installed, you can immediately use LESS syntax within the <style> block of your components by specifying the language attribute:
<style lang="less" scoped>
@primary-color: #1890ff;
.container {
.inner-box {
height: 50px;
width: 50px;
background-color: @primary-color;
}
}
</style>
3. Configure Global Injection
To make variables globally accessible (e.g., defining colors or fonts in a file like src/styles/variables.less), you must configure Vite's CSS preprocessor options. Open vite.config.js and add the css configuration block.
We use the modifyVars option combined with a hack to inject the import statement globally. We also enable javascriptEnabled in case your LESS files contain JS logic.
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { fileURLToPath, URL } from 'node:url'
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
},
css: {
preprocessorOptions: {
less: {
// Inject global files
modifyVars: {
hack: `true; @import "@{src}/styles/variables.less";`
},
javascriptEnabled: true
}
}
}
})
With this configuraton, any variable defined in @/styles/variables.less (e.g., @theme-color: #333;) can be used directly in any component's style block.