vite构建项目:cnpm i vite-app 项目名称(选择了ts、vue3)。
安装路由:cnpm i vue-router。
安装element-plus:cnpm i element-plus -D
安装按需引入element:npm install -D unplugin-vue-components unplugin-auto-import
安装path模块:cnpm i @types/node -D
根目录新建router文件夹,
配置index.ts文件
- import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
- import Home from './Home';
-
- const routes:Array<RouteRecordRaw> = [...Home];
-
- const router = createRouter({
- history:createWebHistory(),
- routes
- })
-
- export default router;
在Home文件夹创建index.ts文件。配置
- const home = [
- {
- path:'/',
- redirect:'/home'
- },
- {
- path:'/home',
- component:()=>import('@/views/Home.vue'),
- }
- ]
-
- export default home
此处使用到了别名@,需要配置tsconfig.json和vite.config.ts。
tsconfig.json配置添加
- "baseUrl": ".",
- "paths": {
- "@/*":["src/*"]
- }
- },
- "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
- "exclude": ["node_modules"],
vite.config.ts各项配置如下。
- import vue from "@vitejs/plugin-vue";
- import AutoImport from "unplugin-auto-import/vite";
- import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
- import Components from "unplugin-vue-components/vite";
- import { defineConfig, loadEnv } from "vite";
- const path = require('path')
-
- // https://vitejs.dev/config/
- export default defineConfig(({ mode }) => {
- //环境判断
- const serveUrl: string = loadEnv(mode, process.cwd()).VITE_HOST;
- const servePort: number = Number(loadEnv(mode, process.cwd()).VITE_PORT);
- console.log(loadEnv(mode, process.cwd()), "环境配置");
- return {
- //包管理
- plugins: [
- vue(),
- //按需引入element-plus
- AutoImport({
- resolvers: [ElementPlusResolver()],
- }),
- Components({
- resolvers: [ElementPlusResolver()],
- }),
- ],
- //别名
- resolve: {
- alias: {
- "@": path.resolve(__dirname, "src"),
- },
- },
- //服务
- server: {
- open: true,
- host: "0.0.0.0",
- port: servePort,
- //代理
- proxy: {
- "/api": {
- target: "http://baidu.com",
- ws: true,
- changeOrigin: true,
- pathRewrite: {
- "^/api": "/",
- },
- },
- },
- },
- };
- });
如果配置完到了页面上使用@引入文件时报错,Cannot find module ‘xxx‘ or its corresponding type declarations.Vetur
关掉vscode,把项目放到根目录用vscode重新打开,则不会再报这个错。
添加.env、.env.development、.env.production文件。配置可如下
- VITE_MODE = 'env'
- VITE_HOST = /api
- VITE_PORT = 8899
main.ts配置如下
- import router from '@/router/index';
- import * as ElementPlusIconsVue from "@element-plus/icons-vue";
- import { createApp } from "vue";
- import App from "./App.vue";
-
- const app = createApp(App);
- for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
- app.component(key, component);
- }
-
- app.use(router)
- app.mount("#app");