不再需要像vite1一样在别名前后加上/,这和webpack项目配置可以保持一致便于移植,好评!
import path from 'path' // ts报错需要安装 `npm i @types/node -D`
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
"@": path.resolve(__dirname, "src")
}
}
})
并在tsconfig.json
里面添加
"compilerOptions": {
"paths": {
"@/*": ["./src/*"]
}
}
在router/index
中
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import Layout from '@/layout/index.vue'
const routes: Array<RouteRecordRaw> = [
{
path: '/login',
name: 'login',
component: () => import(/* webpackChunkName: 'login' */ '@/views/login/index.vue')
},
{
path: '/',
component: Layout,
meta: {
requiresAuth: true // 自定义数据
},
children: [
{
path: '/',
name: 'home',
component: () => import(/* webpackChunkName: 'home' */ '@/views/home/index.vue')
// meta: {
// requiresAuth: true // 自定义数据
// } // meta 默认就是一空对象
}
]
},
{
path: '/:pathMatch(.*)*', // 捕获所有路由或 404 Not found 路由, 可在括号中加入自定义正则表达式
component: () => import(/* webpackChunkName: '404' */ '@/views/error-page/index.vue')
}
]
const router = createRouter({
history: createWebHashHistory(),
routes
})
export default router
参考文档:捕获所有路由或-404-not-found-路由
vite.config.js
css: {
// 使用scss全局变量
preprocessorOptions: {
scss: {
additionalData: '@import "src/styles/variables.scss";'
}
}
}
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
// 获取原型,绑定参数
app.config.globalProperties.name = 'Jerry'
组件内使用
<script setup>
import { getCurrentInstance } from 'vue'
// 获取原型
const { proxy } = getCurrentInstance()
// 输出
console.log(proxy.name)
</script>
module.exports = {
env: {
'vue/setup-compiler-macros': true // 编译器宏,例如defineProps和defineEmits生成no-undef警告
}
}
根目录新建文件 .env.development
, .env.production
# just a flag
NODE_ENV = 'development'
# base api
VITE_APP_BASE_API = '/api'
使用环境变量
import.meta.env.VITE_APP_BASE_API
Pinia 快速上手