初始化项目
Vite 需要 Node.js 版本 >= 12.0.0。
npm init vite@latest
选择vue vue-ts即可生成项目文件
配置vue-router
npm install vue-router@4
main.js里配置路由
import {createRouter, createWebHashHistory} from 'vue-router'
const Home = { template: '<div>Home</div>' }
const About = { template: '<div>About</div>' }
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
]
const router = createRouter({
history: createWebHashHistory(),
routes,
})
app.use(router)
App.vue配置路由视图
<template>
<router-view></router-view>
</template>
碰到warnning: 大概意思是组件提供了template选项,但是这个构建版本的vue不支持运行时编译,所以需要配置vue文件依赖vue/dist/vue.esm-bundler.js
Component provided template option but runtime compilation is not supported in this build of Vue. Configure your bundler to alias "vue" to "vue/dist/vue.esm-bundler.js".
解决方法: vite.config.ts配置依赖
resolve: {
alias: {
'vue': 'vue/dist/vue.esm-bundler.js',
},
}
也可以通过以下方式导入路由,顺便做个路由懒加载
import {createRouter, createWebHashHistory} from 'vue-router'
const routes = [
{ path: '/', component: () => import('./page/home.vue') },
]
const router = createRouter({
history: createWebHashHistory(),
routes,
})
app.use(router)
再顺便配置一下文件别名:
vite.config.ts
resolve: {
alias: {
'@': path.resolve(__dirname, 'src') // 还需要同步配置tsconfig @别名路径
},
}
tsconfig.json
{
"compilerOptions": {
"paths": {
"@": ["src"],
"@/*": ["src/*"],
},
},
}