vue3+vite+ts 项目总结

231 阅读2分钟

这是我参与2022首次更文挑战的第19天,活动详情查看:2022首次更文挑战

Vue 3 + Typescript + Vite

记录一下使用 vue3.x 的时候遇到的一些问题以及解决方案

一、创建项目

yarn create @vitejs/app 或者 yarn create vite vue3Test --template vue
yarn add vue-router@4

1、使用路由

创建 src/router/index.ts 文件
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/test',
    name: 'test',
    component: () => import(/* webpackChunkName: "Home" */ '@/views/test.vue')
  },
  { path: '/', redirect: { name: 'test' } }
]

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

export default router

main.ts 文件中挂载

import { createApp } from 'vue'
import App from '@/App.vue'

import router from '@/router/index'

createApp(App).use(router).mount('#app')

npm i sass -D 安装 sass

2、集成 EditorConfig 配置

EditorConfig 有助于为不同 IDE 编辑器上处理同一项目的多个开发人员维护一致的代码风格。

官网:editorconfig.org

在项目的根目录下创建 .editorconfig 文件:

# Editor configuration, see http://editorconfig.org

# 表示是最顶层的 EditorConfig 配置文件
root = true

[*] # 表示所有文件适用
charset = utf-8 # 设置文件字符集为 utf-8
indent_style = space # 缩进风格(tab | space)
indent_size = 2 # 缩进大小
end_of_line = lf # 控制换行类型(lf | cr | crlf)
trim_trailing_whitespace = true # 去除行首的任意空白字符
insert_final_newline = true # 始终在文件末尾插入一个新行

[*.md] # 表示仅 md 文件适用以下规则
max_line_length = off
trim_trailing_whitespace = false

3、别名

运行报错 这个项目是因为识别不了 @

npm i @types/node -D
修改 vite.config.js
import { defineConfig } from 'vite'
import { resolve } from 'path'

export default defineConfig {
    // ...
    resolve: {
        alias: {
            "@": resolve(__dirname, 'src'), // 路径别名
        },
        extensions: ['.js', '.json', '.ts'] // 使用路径别名时想要省略的后缀名,可以自己 增减
    }
    // ...
}

vite 官方文档中 不建议忽略 .vue 后缀的文,所以在 import 引入文件的时候需要加 .vue cn.vitejs.dev/config/#res…

修改 tsconfig.json

{
    "compilerOptions" : {
        // ...
        "baseUrl": ".", // 用于设置解析非相对模块名称的基本目录,相对模块不会受到baseUrl的影响
        "paths": { // 用于设置模块名到基于baseUrl的路径映射
            "@/*": ["src/*"]
        }
        // ...
    }
}

4、test 文件中使用了 tsx

yarn add @vitejs/plugin-vue-jsx

import vueJsx from '@vitejs/plugin-vue-jsx'
export default defineConfig({
 plugins: [ vueJsx()]
})

tsconfig.json 文件中

{
  // include 需要包含tsx
"include": ["src/*", "src/**/*.vue", "src/**/*.tsx", "src/**/*.jsx", "src/**/*.ts", "src/**/*.js"],
 "compilerOptions": {
    // 在.tsx文件里支持JSX
    "jsx": "preserve",
 }
}