Vue 3 + TypeScript + Vite + Element-Plus
环境支持
由于 Vue 3 不再支持 IE11,Element Plus 也不再支持 IE 浏览器。
Edge ≥ 79 Firefox ≥ 78 Chrome ≥ 64 Safari ≥ 12
1. 使用vite安装Vue3
npm create vite@latest my-vue-app -- --template vue-ts
2. 安装element-plus,并引入
npm install element-plus --save
// main.ts
import { createApp } from 'vue'
import './style.css'
++ import ElementPlus from 'element-plus'
++ import 'element-plus/dist/index.css'
import App from './App.vue'
const app = createApp(App)
++ app.use(ElementPlus)
app.mount('#app')
3. vscode关于vue3+ts的插件
Volar为vue3开发,vetur主要是vue2,如果共存,就会报“has no default export”的错误
- Vue Language Features (Volar)——vue3的代码高亮及语法提示
- TypeScript Vue Plugin (Volar)——支持ts的vue3代码提示
- Vue VSCode Snippets——快速生成各种代码片段
4. 配置vite.config.ts(含修改端口方式)
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
server: {
port: 8080,
}
})
5. 找不到模块“vue”或其相应的类型声明——解决
发现只是没有@types/node声明文件包产生的问题
- 安装
@types/node
文件包:
npm i --save-dev @types/node
- 在typescript对应的编译配置文件tsconfig.json写入以下代码:
"compilerOptions": {
...
"types": [
"node"
],
},
6.vite vue-ts 配置 “@” 路径别名
- 修改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
例 import HelloWorld from ‘@/components/HelloWorld.vue’
- 修改tsconfig.json
{
"compilerOptions" : {
// ...
"baseUrl": ".", // 用于设置解析非相对模块名称的基本目录,相对模块不会受到baseUrl的影响
"paths": { // 用于设置模块名到基于baseUrl的路径映射
"@/*": ["src/*"]
}
// ...
}
}