从0开始搭建vue3+vite+ts+Ant Design Vue项目

376 阅读1分钟

1.使用vite搭建vue3项目

vitejs.cn/guide/#scaf… vite官网(可查看搭建命令,如下)本次项目采用了yarn 来安装项目中的依赖包

# npm 6.x
npm init vite@latest my-vue-app --template vue

# npm 7+, 需要额外的双横线:
npm init vite@latest my-vue-app -- --template vue

# yarn
yarn create vite my-vue-app --template vue

# pnpm
pnpm create vite my-vue-app -- --template vue

2.安装vue-router

使用yarn安装vue-router

yarn add vue-router@4

新建router文件夹

在项目src文件夹下新建router文件夹,并且在router文件夹下新建index.ts,如下图:

1657875421434.jpg

index.ts

import { createRouter,createWebHashHistory, RouteRecordRaw} from 'vue-router' 
import HelloWorld from '/@/components/HelloWorld.vue' 
const routes: Array<RouteRecordRaw> = [ { path: '/', name: 'HelloWorld', component: HelloWorld } ] 
const router = createRouter({ history: createWebHashHistory(), routes }) 
export default router
代码中的 /@ 需要在vite.config.js做了一个路径映射同时在tsconfig.json文件做个映射才可以使用

vite.config.ts

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'; // 主要用于alias文件路径别名

function pathResolve(dir: string) {
  return resolve(__dirname, '.', dir);
}

export default defineConfig({
  plugins: [vue()], // 配置需要使用的插件列表
  resolve: {
    alias: {
      "/@/": pathResolve("src")+'/', // 这里是将src目录配置别名为 /@ 方便在项目中导入src目录下的文件
    }
  },
})

tsconfig.json

{
    "compilerOptions": {
        "allowSyntheticDefaultImports": true,
        "baseUrl": ".",
        "paths": {
            "/@/*": ["src/*"]
        }
    },
    "include": [
        "src/vue.d.ts",
        "src/**/*.ts",
        "src/**/*.d.ts",
        "src/**/*.tsx",
        "src/**/*.vue",
        "vite.config.ts"
      ],
    "exclude": [
        "node_modules",
        "dist"
    ]
}

3.在main.ts文件中引入router

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
createApp(App)
.use(router)
.mount('#app')

4.yarn dev 启动项目

5.完美启动项目

1657782170254.jpg