创建vue3+TS+Vite项目

393 阅读3分钟

安装vite

npm create vite@latest 
或
 yarn create vite

报错

create-vite@4.3.2: The engine "node" is incompatible with this module. Expected version "^14.18.0 || >=16.0.0". Got "14.17.6"

需要node版本14.18.0,或者大于16

最终生成的目录结构

使用yarn安装

yarn

生成一个yarn.lock文件

执行yarn dev

vite默认支持的插件

  • Vite支持在项目中开箱即用的使用.ts文件。
  • Vite提供开箱即用的.jsx和.tsx文件支持,默认支持React16特性
  • vue
  • Vite内置了对.scss, .sass, .less, .styl 和 .stylus文件的支持
  • JSON文件支持直接引入和命名引入:
  • 导入一个静态资源时会返回给使用者一个解析过的公共URL
  • Vite支持批量引入模块。方法是只需要通过import.meta.glob函数
  • 预编译的.wasm文件可以直接引入。文件的默认导出是一个初始化函数,函数返回一个wasm实例的导出对象的Promise:
  • 一个web worker脚本可以通过添加引入参数?worker的方式直接引入。

安装less或sass

Vite内置了对.scss, .sass, .less, .styl 和 .stylus文件的支持。因此不用再为这些文件额外安装适配Vite的插件,但还是要安装相应的预处理器本身。

yarn默认安装到生产环境

yarn add less --dev/-D

yarn remove less //移除插件

  • vite直接支持postcss的转换:
  • 只需要安装postcss,并且配置 postcss.config.js 的配置文件即可

安装路由

1.安装vue-router

yarn add vue-router@4

2.创建 src/router/index.ts 文件

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

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

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

export default router

3.main.ts 文件中挂载

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

import router from '@/router/index'

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

4.app.ts中设置路由,同时删除HelloWord.vue

<template>
  <router-view />
</template>

<script setup lang="ts">
</script>

安装ant-design

yarn add ant-design-vue@next

main.ts

import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from './router/index';
+import { Button, message } from 'ant-design-vue';

+let app=createApp(App)
+app.use(router)
+.use(Button)
.mount('#app')
+app.config.globalProperties.$message = message;

报错

// import 'ant-design-vue/dist/antd.css'; // 要引入才有样式

把样式去除就不报错了

问题

问题一:yarn build 路径为绝对路径,如何改为相对路径

方法: 在defineConfig中添加 base: “./” (绝对路径用/)

在vscode中ts引入vue路径会被报错

代码编辑器:vscode ,使用vue3,所以安装了 Volar 插件,可以使 vue 代码高亮显示,不同颜色区分代码块,以及语法错误提示等

提示:如果使用的是vue2,则使用 Vetur 插件;使用 vue3 的话 ,要禁用 Vetur 插件,然后用 Volar 插件。两个插件不要同时使用,会冲突。

错描述:

安装vite框架(Vue3)后,项目“main.ts” 文件中 “import App from ‘./App.vue’” 部分有红色报错提示,其他文件有些import引入文件也报错。

查看项目“main.ts” 文件中 “import App from ‘./App.vue’” 部分报错原因,提示报错 “Cannot find module ‘./App.vue’ or its corresponding type declaration”

报错原因:vite使用的是ts,ts不识别 .vue 后缀的文件

解决方法:

创建vite项目后,项目根目录会有一个 “vite-env.d.ts” 文件,找到该文件,在里面添加一下代码:

declare module "*.vue" {
  import { DefineComponent } from "vue"
  const component: DefineComponent<{}, {}, any>
  export default component
}

注意:引用vue文件时不可省略后缀,不然识别不到会报错。

总结

我们看到启动程序vite基本上没有任何配置,内部已经支持了基本应用的loader使用,vue本地也很快。