使用Vite2+TypeScript4+Vue3技术栈,如何入手开发项目

前端简报

共 8941字,需浏览 18分钟

 · 2021-04-14

点击上方“前端简报”,选择“设为星标

第一时间关注技术干货!


前言

已经两周没有发文了,自己临时有点事耽误了,在这里向大家表示深深地歉意。今天,我们使用vite2.0+vue3+ts来开发一个demo项目。

实战

我们,打开Vite官方网站(https://cn.vitejs.dev/)。

Vite (法语意为 "快速的",发音 /vit/) 是一种新型前端构建工具,能够显著提升前端开发体验。它主要由两部分组成:
一个开发服务器,它基于 原生 ES 模块 提供了 丰富的内建功能,如速度快到惊人的 模块热更新(HMR)。
一套构建指令,它使用 Rollup 打包你的代码,并且它是预配置的,可以输出用于生产环境的优化过的静态资源。
Vite 意在提供开箱即用的配置,同时它的 插件 API 和 JavaScript API 带来了高度的可扩展性,并有完整的类型支持。

这里,我们将Vite与VueCLI做一下对比。

  • Vite在开发模式下不需要打包可以直接运行,使用的是ES6的模块化加载规则;

  • VueCLI开发模式下必须对项目打包才可以运行;

  • Vite基于缓存的热更新;

  • VueCLI基于webpack的热更新;

搭建项目

我们来搭建第一个 Vite 项目,我这里使用Yarn依赖管理工具进行创建项目。

yarn create @vitejs/app

在命令行键入以上命令,然后你可能会等待一会儿~

依次配置Project nameSelect a template

Project name: vite-vue-demo

Select a template: vue-ts

因为,我们这里要是用Vue+Ts开发项目所以我们选择vue-ts这个模板。一顿操作之后,会提示你键入以下命令,依次填入即可。

cd vite-vue-demo
yarn
yarn dev

这样我们搭建项目就完成了。

项目文件夹一览

我们会看到以下文件及其文件夹。

node_modules  ---依赖文件夹
public ---公共文件夹
src ---项目主要文件夹
.gitignore ---排除git提交配置文件
index.html ---入口文件
package.json ---模块描述文件
tsconfig.json ---ts配置文件
vite.config.ts ---vite配置文件

开发前配置

在开发之前呢,我们需要做以下工作。

1. 编辑ts配置文件

根据需要,配置需要的配置项。compilerOptions里面配置的是编译时的配置项,include项是配置生效包括在内的路径,而exclude则恰恰相反,排除在外的路径。

{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"strict": true,
"jsx": "preserve",
"importHelpers": true,
"moduleResolution": "node",
"experimentalDecorators": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"baseUrl": ".",
"types": ["vite/client"],
"paths": {
"@/*": [
"src/*"
]
},
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"tests/**/*.ts",
"tests/**/*.tsx"
],
"exclude": [
"node_modules"
]
}

2. 配置vite配置文件

为什么需要配置这个文件呢?是因为我们开发这个demo项目,需要局部引入Element Plus UI框架,另外,让我们简单了解下怎么配置Vite。在之前我们使用VueCLI3.x创建项目时配置项目是在根目录下vue.config.js文件下进行配置。这个文件应该导出一个包含了选项的对象。

module.exports = {
// 选项...
}

vite.config.ts也与其相似。

export default {
// 配置选项
}

因为 Vite 本身附带 Typescript 类型,所以可以通过 IDE 和 jsdoc 的配合来进行智能提示,另外你可以使用 defineConfig 帮手函数,这样不用 jsdoc 注解也可以获取类型提示。这里呢,我们这样配置vite.config.ts

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()]
})

你会发现,Vue在这里被当做vite的一个内置插件引入进来。刚才,我们说要局部引入Element Plus UI框架,我们打开Element Plus UI局部引入网址:(https://element-plus.gitee.io/#/zh-CN/component/quickstart),发现这里需要配置babel.config.js,而我们使用的是TS,所以我们下意识的更改下后缀名觉得就可以成功了,不过,我反正被坑了。于是,采取了这种办法:在vite.config.ts文件中这样配置:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vitePluginImp from "vite-plugin-imp";

// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue(),
vitePluginImp({
libList: [
{
libName: 'element-plus',
style: (name) => {
return`element-plus/lib/theme-chalk/${name}.css`
}
}
]
})],
server: {
port: 6061
},
})

vite-plugin-imp一个自动导入组件库样式的vite插件。

主要项目文件夹Src一览

以下是最初始的项目文件目录。

assets  ---静态文件夹
components ---组件文件夹
App.vue ---页面文件
main.ts ---项目入口文件
shims-vue.d.ts ---类型定义文件(描述文件)

这么多文件,我们不一一展示了,主要看下App.vuemain.tsshims-vue.d.ts

App.vue

<template>
<img alt="Vue logo" src="./assets/logo.png" />
<HelloWorld msg="Hello Vue 3 + TypeScript + Vite" />
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import HelloWorld from './components/HelloWorld.vue'

export default defineComponent({
name: 'App',
components: {
HelloWorld
}
})
</script>

<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>

main.ts

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

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

shims-vue.d.ts

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

这里,我们看到defineComponent这个Vue3的一个方法。为什么这里会使用它呢?引用官方的一句话:

从实现上看,defineComponent 只返回传递给它的对象。但是,就类型而言,返回的值有一个合成类型的构造函数,用于手动渲染函数、TSX 和 IDE 工具支持。

引入vue-router4

看完之前的基础配置,我们现在准备开始引入Vue3的生态系统。

现在我们安装 vue-router 版本的时候,默认还是安装的 3.x 版本的,由于 vue3 的更新发生很大的变化,所以为了兼容处理,vue-router 也将发布最新版 4.x 版本了。

这是router4的官方网址:

https://next.router.vuejs.org/

1. 安装

npm install vue-router@4

2. 配置文件

安装完依赖后,在项目文件夹src下创建一个router文件夹,里面创建一个index.ts文件(因为这里我们基于TS的项目)。

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

const routes: Array<RouteRecordRaw> = [
{
path: "/",
name: "Home",
component: Home
},
{
path: "/about",
name: "About",
component: () =>
import("../views/About.vue")
}
];

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

export default router;

另外,你需要在main.ts文件中引入它,并且注册一下。

import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";

createApp(App).use(router).mount("#app");

为了实验一下效果,我们在src文件夹下创建一个views文件夹,里面创建两个页面文件。分别是About.vueHome.vue

home.vue

<template>
<p class="txt">home</p>
</template>

<script lang="ts">
import { Options, Vue } from "vue-class-component";

@Options({

})
export default class Home extends Vue {}
</script>

<style scoped>
.txt{
color: red;
}
</style>

about.vue

<template>
<p>about</p>
</template>

<script>
export default {
name: "About"
}
</script>

最后,你在App.vue文件中。

<template>
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
<router-view />
</template>

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

这样,vue-router4就这么成功引入了。

引入css预处理语言

这里呢,我们引入scss。因为我们使用的vite这个构建工具构建的项目,所以我们只需要这样。

npm install -D sass

我们可以看到官方解释:

Vite 同时提供了对 .scss, .sass, .less, .styl 和 .stylus 文件的内置支持。没有必要为他们安装特定的 vite 插件,但相应的预处理器依赖本身必须安装。

所以,你可以这样使用scss。

<template>
<p class="txt">home</p>
</template>

<script lang="ts">
import { Options, Vue } from "vue-class-component";

@Options({

})
export default class Home extends Vue {}
</script>

<style scoped lang="scss">
.txt{
color: red;
}
</style>

使用Element Plus UI

我们在上面已经成功配置局部引入Element Plus框架,那我们可以这样使用它。

<template>
<p class="txt">home</p>
<ElButton>默认按钮</ElButton>
</template>

<script lang="ts">
import { Options, Vue } from "vue-class-component";
import { ElButton } from 'element-plus'

@Options({
components: {
ElButton
}
})
export default class Home extends Vue {}
</script>

<style scoped lang="scss">
.txt{
color: red;
}
</style>

这里,你会发现引入了 vue-class-component这个组件,它是干什么的呢?

官方网址:

https://class-component.vuejs.org/

Vue Class Component is a library that lets you make your Vue components in class-style syntax.

译:Vue类组件是一个库,允许您以类样式语法创建Vue组件。

针对vue3版本,我们使用Vue Class Component v8,也就是8版本。

https://www.npmjs.com/package/vue-class-component/v/8.0.0-rc.1

你可以这样安装它。

npm i vue-class-component@8.0.0-rc.1

引入vue自定义组件

我们经常自己封装组件,那么在这个项目中我们是怎样引入的呢?我们在src目录下创建一个components文件夹,里面创建一个HelloWorld.vue文件。

HelloWorld.vue

<template>
<h1>{{ msg }}</h1>
</template>

<script lang="ts">
import { ref, defineComponent } from 'vue'
export default defineComponent({
name: 'HelloWorld',
props: {
msg: {
type: String,
required: true
}
},
setup: () => {
const count = ref(0)
return { count }
}
})
</script>

<style scoped lang="scss">
a {
color: #42b983;
}

label {
margin: 0 0.5em;
font-weight: bold;
}

code {
background-color: #eee;
padding: 2px 4px;
border-radius: 4px;
color: #304455;
}
</style>

然后,我们在App.vue引入它。

<template>
<HelloWorld msg="Hello Vue 3 + TypeScript + Vite" />
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
<router-view />
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import HelloWorld from './components/HelloWorld.vue'

export default defineComponent({
name: 'App',
components: {
HelloWorld
}
})
</script>

<style >
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
</style>

引入vuex4

vue生态中肯定少不了vuex,为了兼容vue3,vuex也推出了4.0版本。

https://next.vuex.vuejs.org/

你可以这样安装它。

npm install vuex@next --save

你可以在src文件夹创建一个store文件夹,里面创建一个一个index.ts文件。

import { createStore } from "vuex";

export default createStore({
state: {},
mutations: {},
actions: {},
modules: {}
});

然后,你在main.ts文件中这样引入使用它。

import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";

createApp(App).use(router).use(store)
.mount("#app");

结语


我们这里只是简单地使用vite+ts+vue3搭建了一个小demo,如果你想更深层地使用它,可以关注我的动态。

浏览 42
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报