vite+vue3+typescript搭建项目入门

尤大的vue3发布已经有一段时间了,其官方脚手架创建项目已经默认使用vue3版本,看来是时候拥抱vue3用于正式的生产环境了。当然,因为vue3typescript有着相比vue2更好的支持,本身vue3也是用typescript写的,喜欢折腾学习新知识的可以尝试使用typescript,还有尤大的vite,利用现代浏览器的特性能让咱们拥有不管项目大小都能快速刷新的神器。
基于以上种种,笔者尝试用vite+vue3+typescript搭建一个项目。

新建项目

vite的使用方法可以看看官方文档,这里就不做过多的赘述。

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

文件改造

稍具规模的项目肯定少不了VueRouterelement-plus等插件和第三方UI框架。

笔者习惯单独设置一个文件去配置,如router.ts,在定义routes的时候会提示设置数据类型,开始的时候比较懵,后来发现可以import需要的数据类型来配置,大概如下:

import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import Home from '../views/Home/index.vue'

const routes:RouteRecordRaw[] = [{
  path: '/',
  name: 'home',
  component: Home
}]

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

export default router

element-plus支持自动导入,配置请自行查看element-plus文档,所以我习惯单独import组件注册组件的ui.ts,只引入项目中使用到的组件,内容大致如下:

import { App } from 'vue'
import {
  ElButton
} from 'element-plus'

const ui = (app:App) => {
  app.use(ElButton)
}

export default ui

为了正常挂载router等,main.ts还需要做一番调整,改造后大致内容如下:

import { createApp } from 'vue'
import App from './App.vue'
import ui from './plugin/index'
import store from './store/index'
import router from './router/index'


const app = createApp(App)
ui(app)
app.use(store)
app.use(router)
app.mount('#app')

tsconfig.json的配置

  1. 允许使用javascript;
    同一个项目,可能有些开发人员不习惯用ts或者短时间内不会ts,则可以开启允许js的设置,这样在.vue组件里可以使用js来开发,而不必一定要

你可能感兴趣的:(vite+vue3+typescript搭建项目入门)