vue实现预处理
预处理的概念
预处理是指在代码编译或运行前对源代码进行一系列处理操作,例如变量替换、代码压缩、条件编译等。在Vue项目中,预处理通常通过构建工具(如Webpack或Vite)结合预处理器(如Sass、Less、PostCSS)实现。
使用预处理器处理样式
Vue单文件组件(.vue文件)支持通过<style>标签的lang属性指定预处理器。例如使用Sass/SCSS:
<style lang="scss">
$primary-color: #42b983;
.button {
background: $primary-color;
}
</style>
需先安装对应预处理器:
npm install sass --save-dev
模板预处理
通过<template>标签的lang属性可指定Pug等模板引擎:
<template lang="pug">
div.container
h1 {{ title }}
button(@click="handleClick") Click
</template>
需安装pug相关依赖:

npm install pug pug-plain-loader --save-dev
JavaScript预处理
在<script>标签中使用TypeScript或Babel转译:
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
data() {
return { count: 0 }
}
})
</script>
需配置对应的loader(如ts-loader)和tsconfig.json文件。
构建工具配置
在vite.config.js或webpack.config.js中配置预处理器支持。以Vite为例:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue({
template: {
compilerOptions: {
// pug相关配置
}
}
})],
css: {
preprocessorOptions: {
scss: {
additionalData: `@import "@/styles/variables.scss";`
}
}
}
})
环境变量预处理
在项目根目录创建.env文件定义环境变量:
VITE_API_URL=https://api.example.com
通过import.meta.env访问:
const apiUrl = import.meta.env.VITE_API_URL
自定义预处理
可通过编写Webpack loader或Vite插件实现自定义预处理逻辑。例如创建自定义markdown处理:
// vite.config.js
import markdown from './markdown-plugin'
export default defineConfig({
plugins: [markdown(), vue()]
})






