Vue 3 + TypeScript + Vite 搭建初始项目

8,138 阅读2分钟

技术栈:Vue3 + TypeScript + Vite + Vant + Pinia

环境:

  • node v16.15.1 (node -v)
  • npm v8.11.0 (npm -v)
  • @vue/cli 5.0.6 (vue -V)

搭建项目

使用 Vite 构建项目

$ npm create vite@latest vue3-ts-vite-vant-seed -- --template vue-ts
$ cd vue3-ts-vite-vant-seed
$ npm install
$ npm run dev

修改 Vite 配置文件

Vite 配置文件 vite.config.ts 位于根目录下,项目启动时会自动读取。

简单配置如:设置 @ 指向 src 目录、 服务启动端口、打包路径、代理等。

关于 Vite 更多配置项及用法,请查看 Vite 官网 vitejs.dev/config/

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
// 如果编辑器提示 path 模块找不到,则可以安装一下 @types/node -> npm i @types/node -D
import { resolve } from "path";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      "@": resolve(__dirname, "src"), // 设置 `@` 指向 `src` 目录
    },
  },
  base: "./", // 设置打包路径
  server: {
    port: 4000, // 设置服务启动端口号
    open: true, // 设置服务启动时是否自动打开浏览器
    cors: true, // 允许跨域

    // 设置代理,根据我们项目实际情况配置
    // proxy: {
    //   '/api': {
    //     target: 'http://xxx.xxx.xxx.xxx:8000',
    //     changeOrigin: true,
    //     secure: false,
    //     rewrite: (path) => path.replace('/api/', '/')
    //   }
    // }
  },
});

配置别名还是找不到, tsconfig.json 即可解决

// tsconfig.json
{
  "compilerOptions": {
    "paths": {
      "@/*": ["./src/*"],
    }
  }
}

Cannot find module '@/views/home.vue' or its corresponding type declarations.ts

vscode F1 volar: select typescript version -- use workspace version

规范目录结构

├── dist/
└── src/
    ├── api
    │   └── ... // 抽取出API请求
    ├── assets/                    // 静态资源目录
    ├── common/                    // 通用类库目录
    ├── components/                // 公共组件目录
    ├── router/                    // 路由配置目录
    ├── store/                     // pinia 状态管理目录
        ├── index.ts               // 导出 store 的地方
        ├── home.ts                // 模块
        └── user.ts                // 模块
    ├── style/                     // 通用 CSS 目录
    ├── utils/                     // 工具函数目录
    ├── views/                     // 页面组件目录
    ├── App.vue
    ├── main.ts
    ├── vite-env.d.ts
├── index.html
├── tsconfig.json                  // TypeScript 配置文件
├── vite.config.ts                 // Vite 配置文件
└── package.json

创建对应的文件夹

集成路由工具 Vue Router 4.x

router.vuejs.org/zh/installa…

  1. 安装

    $ npm i vue-router@4
    
  2. 在  src/views  目录下创建  home.vue 、user.vue ,并修改App.vue

    home.vue:

    <template> 这是home.vue </template>
    

    user.vue:

    <template> 这是user.vue </template>
    

    APP.vue:

    <template>
      <router-view />
    </template>
    
  3. 创建  src/router/index.ts  文件,配置路由

    import {
      createRouter,
      createWebHashHistory,
      RouteRecordRaw,
    } from "vue-router";
    
    import Home from "@/views/home.vue";
    import User from "@/views/user.vue";
    
    const routes: Array<RouteRecordRaw> = [
      {
        path: "/",
        redirect: "/home",
      },
      {
        path: "/home",
        name: "home",
        component: Home,
      },
      {
        path: "/user",
        name: "user",
        component: User,
      },
    ];
    
    const router = createRouter({
      history: createWebHashHistory(),
      routes,
    });
    
    export default router;
    
  4. 在  main.ts  文件中挂载路由配置

    import { createApp } from "vue";
    import App from "./App.vue";
    import router from "./router/index";
    createApp(App).use(router).mount("#app");
    
  5. 路由访问 home、user

集成 UI 框架 Vant

vant-ui.github.io/vant/#/en-U…

  1. 安装支持 vue3 的 vant

    $ npm i vant
    
  2. 引入组件

    对于 vite 项目,可以使用 unplugin-vue-components 实现按需引入

    安装插件:

    $ npm i unplugin-vue-components -D
    

    修改vite.config.ts部分配置:

    import vue from '@vitejs/plugin-vue';
    import Components from 'unplugin-vue-components/vite';
    import { VantResolver } from 'unplugin-vue-components/resolvers';
    
    export default {
    plugins: [
      vue(),
      Components({
         resolvers: [VantResolver()],
      }),
    ],
    };
    
  3. 修改App.vue,增加底部tab导航,即可看到效果

    // App.vue
    <template>
      <router-view />
      <van-tabbar v-model="active">
        <van-tabbar-item icon="home-o" to="/home">首页</van-tabbar-item>
        <van-tabbar-item icon="contact" to="/user">我的</van-tabbar-item>
      </van-tabbar>
    </template>
    <script setup lang="ts">
      import { ref } from 'vue';
      const active = ref(0);
    </script>
    

集成状态管理工具 Pinia

pinia.vuejs.org/zh/introduc…

  1. 安装

    $ npm i pinia
    
  2. store/index.ts

    import { createPinia } from 'pinia'
    // import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
    // import { PiniaLoading } from '@/utils/piniaLoading'
    
    const pinia = createPinia()
    // pinia.use(piniaPluginPersistedstate)
    // pinia.use(PiniaLoading)
    export default pinia;
    
  3. main.ts

    import { createApp } from 'vue'
    import App from './App.vue'
    import router from './router/index'
    import pinia from './store';
    
    createApp(App)
    .use(router)
    .use(pinia)
    .mount('#app')
    
  4. store/home.ts

import { defineStore } from "pinia"

export const useHomeStore = defineStore('home', {
    state: () => ({ count: 0 }),
    getters: {
        double: (state) => state.count * 2,
    },
    actions: {
        increment() {
            this.count++
        },
    },
})
  1. views/home.vue
<template> 这是home.vue {{ store.count }}</template>

<script setup lang="ts">
  import { useHomeStore } from '@/store/home'
  const store = useHomeStore()
</script>

集成 HTTP 工具 Axios

  1. 安装 Axios(Axios 跟 Vue 版本没有直接关系,安装最新即可)

    $ npm i axios
    

集成 CSS 预编译器 Stylus/Sass/Less

项目使用 CSS 预编译器 Stylus,直接安装为开发依赖即可。Vite 内部已集成了相关的 loader,不需要额外配置。同理,也可以使用 Sass 或 Less 等。

  1. 安装

    npm i stylus -D
    # or
    npm i sass -D
    npm i less -D
    
  2. 使用

    <style lang="stylus">
      ...
    </style>
    

GitHub Actions 自动部署 gh-pages

传送门 -> GitHub Actions 实现提交代码自动打包部署到 gh-pages

至此,一个基于 TypeScript + Vite + Vue3 + Vue Router + Vuex + Vant + Axios + Stylus/Sass/Less 的前端项目开发环境搭建完毕

待完成