一、创建项目
npm init vue@latest
二、npm 切换淘宝镜像
npm config set registry https://registry.npm.taobao.org
三、解决 引入app.vue 报错
在 src 下得 vite-env.d.ts 中引入以下代码
// 解决 引入app.vue 报错
declare module "*.vue" {
import type { DefineComponent } from "vue";
const vueComponent: DefineComponent<{}, {}, any>;
export default vueComponent;
}
四、解决 在组件中开发无需每次都引入 import { ref } …
1、 安装插件
npm i unplugin-auto-import -D
2、 在 vite.config.ts 中配置以下代码
import AutoImport from 'unplugin-auto-import/vite'
plugins: [
vue(),
AutoImport({
imports: ["vue", "vue-router"], //自动导入vue和vue-router相关函数
}),
],
3、假如出现报错,可能是因为ts没识别到这份文件 你可以在tsconfig.json进行如下配置 把他添加进include
{
"compilerOptions": {
// ...
},
"include": [
"src/**/*.ts",
"src/**/*.d.ts",
"src/**/*.tsx",
"src/**/*.vue",
"./auto-imports.d.ts"
],
}
4、使用
<script setup lang="ts">
// import { ref } from 'vue'
let aa = ref(0)
</script>
<template>
{{ aa }}
</template>
五、解决 import.meta.env.BASE_URL 报错
原因:这是因为没有引入 ImportMeta 的类型声明文件,Vite 有提供 vite/client.d.ts 来做类型声明
解决:在 tsconfig.json 文件 compilerOptions 中 添加 "types": ["vite/client"]
六、配置 @ 指代 src的效果
参考原文
1、安装包
不安装@types/node,__dirname会报错
npm i path
npm i @types/node
2、配置 vite.config.ts 文件
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { resolve } from "path"; // 引入方法
export default defineConfig({
plugins: [vue()],
resolve: {
alias: [ // 配置 @ 指代 src
{
find: "@",
replacement: resolve(__dirname, "./src"),
},
],
}
});
3、配置 tsconfig.json 文件
导入ts文件需要配置,不然会在vscode里报错!!!
{
"compilerOptions": {
...
"baseUrl": ".",
"paths": {
"@/*": [ "src/*" ]
}
},
...
}
七、tsconfig.json 与 tsconfig.node.json 报错
在 两个文件中的 compilerOptions 对象下 添加 “ignoreDeprecations”: “5.0”
参考原文
1、tsconfig.json
{
"extends": "@vue/tsconfig/tsconfig.web.json",
"compilerOptions": {
"ignoreDeprecations": "5.0",
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
},
"types": [
"vite/client"
],
},
"include": [
"src/**/*.ts",
"src/**/*.d.ts",
"src/**/*.tsx",
"src/**/*.vue",
"./auto-imports.d.ts"
],
"references": [
{
"path": "./tsconfig.node.json"
}
]
}
2、tsconfig.node.json
{
"extends": "@vue/tsconfig/tsconfig.node.json",
"include": [
"vite.config.*",
"vitest.config.*",
"cypress.config.*",
"playwright.config.*"
],
"compilerOptions": {
"ignoreDeprecations": "5.0",
"composite": true,
"types": [
"node"
],
}
}