【笔记】使用Vite搭建Vue3(TypeScript版本)项目

1,056 阅读3分钟

前提条件:

  1. 已安装nodejs环境(Tips:Vite 需要 Node.js 版本 >= 12.0.0)
  2. 已安装yarn(可选项)

使用Vite搭建Vue3的TypeScript版本的时候,可以使用Vite自带的模板预设——vue-ts

关于Vue3中的TypeScript使用:在Vue3的单文件组件(SFC)中,<script>已经很好的支持TypeScript,只需要将 标签 的lang属性设置为ts即可。(<script lang="ts">...</script>(原文))。

以下步骤,如果熟悉安装的一些细节问题,则可以跳过Tips,只关注命令行和代码即可。

1. 搭建Vue3(ts)基础环境:安装模板预设

1.1 在工作区文件夹下,执行命令行

Tips: 安装预设模板时,命令行会自动新建一个 项目名 (命令行里的PROJECT_NAME) 的文件夹,因此在 工作区文件夹 下,不需要提前新建一个项目名的文件夹。避免重复项目名文件夹中还有一个项目名文件夹,即项目名为example,如果在新建的项目名文件夹(example)下执行命令,并将命令中PROJECT_NAME命名为example,那么最后的文件路径将会是example/example

命令行(视情况选其一)

# 命令中的 PROJECT_NAME 需要替换为自己的 项目名称 

# npm 6.x
npm init vite@latest PROJECT_NAME --template vue-ts

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

# yarn
yarn create vite PROJECT_NAME --template vue-ts

1.2 安装基础环境的相关包

创建完成之后,使用命令npm i/npm install或者yarn安装基础环境的相关包。

1.3 测试项目可运行性

环境安装之后,使用命令npm run dev或者yarn dev测试项目是否可以运行成功。

2. 安装Vue-Router

2.1 执行命令行

安装最新版本(@next);以下命令视情况选其一。

# npm
npm install vue-router@next
# yarn
yarn add vue-router@next

Tips

  1. 在Vue3版本下,建议使用Vue-Router4原文)。
  2. 如需要自定义相应版本,将@后next改为对应版本号即可。

2.2 创建相应文件

视个人情况,可以选择,如在src文件夹下新建router文件夹,然后新建index.ts文件,也可以直接新建router.ts文件。

router.ts/index.ts

import { createRouter, createWebHistory } from 'vue-router'

export default createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      component: () => import('./views/Home.vue')
    },
    // ...其他路由配置
  ]
});

2.3. main.ts文件配置

将新建的router文件添加全局注册到main.ts文件。

main.ts

import { createApp } from 'vue'
// 新增内容 >>>>> 
import router from './router'
// <<<
import App from './App.vue'

const app = createApp(App)

// 新增内容 >>>>>
app.use(router)
// <<<<<
app.mount('#app')

2.4 Vue-Router的使用(选看)

在Vue3中,使用方法或者函数通常建议按需导入的方式去使用Vue-Router本身的方法。 在main.ts注册完成之后,在<script setup lang="ts">或者<script lang="ts">中按需导入需要使用其属性和方法即可。

例如:

import { useRouter, useRoute } from 'vue-router';

const router = useRouter();
const route = useRoute();

3. 安装Vuex / Pinia

Pinia是较Vuex,更简洁和更轻量级的状态库,重点针对Vue3设计,因此在Vue3项目中更推荐使用Pinia

3.1 执行命令行

3.1.1 安装Pinia

安装命令选其一:

# npm
npm install pinia
# yarn
yarn add pinia 

3.1.2 安装最新版本Vuex

安装命令选其一:

# npm
npm install vuex@next
# yarn
yarn add vuex@next

Tips:

  1. 在Vue3版本下,需要使用Vuex4才能够正常使用原文)。
  2. 如需要自定义相应版本,将@后next改为对应版本号即可。

3.2 创建相应文件

文件目录相关处理方式同理Vue-route。

3.2.1 Pinia创建和使用

直接摘抄官网

创建:

// stores/counter.js
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
    state: () => {
        return { count: 0 }
    },
    // 也可以这样定义
    // state: () => ({ count: 0 })
    actions: {
        increment() {
            this.count++
        },
    },
})

使用:

<script setup>
import { useCounterStore } from '@/stores/counter'
const counter = useCounterStore()
counter.count++
// 自动补全! ✨
counter.$patch({ count: counter.count + 1 })
// 或使用 action 代替
counter.increment()
</script>
<template>
      <!-- 直接从 store 中访问 state -->
      <div>Current Count: {{ counter.count }}</div>
</template>

3.2.2 Vuex处理

单独按需使用参考链接

全局注册:同Vue-Router模式相同,创建文件,main.ts文件注册。

store.ts/store/index.ts文件:

import { createStore } from 'vuex'

// 创建一个新的 store 实例
export const store = createStore({
  state () {
    return {
      count: 0
    }
  },
  mutations: {
    increment (state) {
      state.count++
    }
  }
})

main.ts文件注册:

import store from './store';

// ... 其他代码

app.use(store)

3.2.3 关于this.$store(选看)

Vuex 没有为 this.$store 属性提供开箱即用的类型声明。如果你要使用 TypeScript,首先需要声明自定义的模块补充(module augmentation)

为此,需要在项目文件夹中添加一个声明文件来声明 Vue 的自定义类型 ComponentCustomProperties

vuex.d.ts

// vuex.d.ts
import { ComponentCustomProperties } from 'vue'
import { Store } from 'vuex'

declare module '@vue/runtime-core' {
  // 声明自己的 store state
  interface State {
    count: number
  }

  // 为 `this.$store` 提供类型声明
  interface ComponentCustomProperties {
    $store: Store<State>
  }
}

当使用组合式 API 编写 Vue 组件时,您可能希望 useStore 返回类型化的 store。为了 useStore 能正确返回类型化的 store,必须执行以下步骤:

  1. 定义类型化的 InjectionKey
  2. 将 store 安装到 Vue 应用时提供类型化的 InjectionKey 。
  3. 将类型化的 InjectionKey 传给 useStore 方法。 store.ts
// store.ts
import { InjectionKey } from 'vue'
import { createStore, useStore as baseUseStore, Store } from 'vuex'

// 为 store state 声明类型
export interface State {
  count: number
}

// 定义 injection key
export const key: InjectionKey<Store<State>> = Symbol()

export const store = createStore<State>({
  state: {
    count: 0
  }
})

// 定义自己的 `useStore` 组合式函数
export function useStore() {
  return baseUseStore(key)
}

4. 补充

4.1 Vue-Router路由自动处理

参考:github.com/pohunchn/vi… router.ts

import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router"

function getRoutes() {
	const { routes } = loadRouters();
	/**
	 * routes处理部分
	 */
	return routes;
}

const router = createRouter({
    history: createWebHashHistory(),
    routes: getRoutes()
})

export default router;

/** 自动化处理view目录下的文件生成为路由 */
function loadRouters() {
    const context = import.meta.globEager("../views/**/*.vue");
    const routes: RouteRecordRaw[] = [];

    Object.keys(context).forEach((key: any) => {
        if (key === "./index.ts") return;
		let name = key.replace(/(\.\.\/views\/|\.vue)/g, '');
		let path = "/" + name.toLowerCase();
		if (name === "Index") path = "/";
		routes.push({
			path: path,
			name: name,
			component: () => import(`../views/${name}.vue`)
		})
    });

    return { context, routes }
}

5. 相关链接

  • 官方相关ts项目示例:vite-ts-quick - Vue 3 + Vuex + Vue-router + TypeScript Quick Template.
  • 官方相关项目示例:Awesome Vite.js

6. Sass/Scss安装

  1. 安装
# npm
npm install sass --save-dev
# yarn
yarn add sass --dev
  1. 使用
<style lang="scss">
...
</style>

7. 测试框架Cypress安装(E2E)

  1. 安装
# npm
npm install cypress --save-dev
# yarn
yarn add cypress --dev
  1. 运行
# npm
npx cypress open
# yarn
yarn run cypress open
  1. package.json文件脚本配置
{
  "scripts": {
    "cypress:open": "cypress open"
  }
}

"cypress:open"可自定义更改,执行命令行时则需要相对应。

  1. 执行命令
# npm
npm run cypress:open
# yarn
yarn cypress:open