使用Vite2+TypeScript4+Vue3技術(shù)棧,如何入手開發(fā)項目
前言
已經(jīng)兩周沒有發(fā)文了,自己臨時有點事耽誤了,在這里向大家表示深深地歉意。今天,我們使用vite2.0+vue3+ts來開發(fā)一個demo項目。
實戰(zhàn)
我們,打開Vite官方網(wǎng)站(https://cn.vitejs.dev/)。
- Vite (法語意為 "快速的",發(fā)音 /vit/) 是一種新型前端構(gòu)建工具,能夠顯著提升前端開發(fā)體驗。它主要由兩部分組成:
- 一個開發(fā)服務(wù)器,它基于 原生 ES 模塊 提供了 豐富的內(nèi)建功能,如速度快到驚人的 模塊熱更新(HMR)。
- 一套構(gòu)建指令,它使用 Rollup 打包你的代碼,并且它是預配置的,可以輸出用于生產(chǎn)環(huán)境的優(yōu)化過的靜態(tài)資源。
- Vite 意在提供開箱即用的配置,同時它的 插件 API 和 JavaScript API 帶來了高度的可擴展性,并有完整的類型支持。
這里,我們將Vite與VueCLI做一下對比。
- Vite在開發(fā)模式下不需要打包可以直接運行,使用的是ES6的模塊化加載規(guī)則;
- VueCLI開發(fā)模式下必須對項目打包才可以運行;
- Vite基于緩存的熱更新;
- VueCLI基于webpack的熱更新;
搭建項目
我們來搭建第一個 Vite 項目,我這里使用Yarn依賴管理工具進行創(chuàng)建項目。
- yarn create @vitejs/app
在命令行鍵入以上命令,然后你可能會等待一會兒~
依次配置Project name、Select a template
- Project name: vite-vue-demo
- Select a template: vue-ts
因為,我們這里要是用Vue+Ts開發(fā)項目所以我們選擇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配置文件
開發(fā)前配置
在開發(fā)之前呢,我們需要做以下工作。
1. 編輯ts配置文件
根據(jù)需要,配置需要的配置項。compilerOptions里面配置的是編譯時的配置項,include項是配置生效包括在內(nèi)的路徑,而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配置文件
為什么需要配置這個文件呢?是因為我們開發(fā)這個demo項目,需要局部引入Element Plus UI框架,另外,讓我們簡單了解下怎么配置Vite。在之前我們使用VueCLI3.x創(chuàng)建項目時配置項目是在根目錄下vue.config.js文件下進行配置。這個文件應該導出一個包含了選項的對象。
- module.exports = {
- // 選項...
- }
而vite.config.ts也與其相似。
- export default {
- // 配置選項
- }
因為 Vite 本身附帶 Typescript 類型,所以可以通過 IDE 和 jsdoc 的配合來進行智能提示,另外你可以使用 defineConfig 幫手函數(shù),這樣不用 jsdoc 注解也可以獲取類型提示。這里呢,我們這樣配置vite.config.ts。
- import { defineConfig } from 'vite'
- import vue from '@vitejs/plugin-vue'
- // https://vitejs.dev/config/
- export default defineConfig({
- plugins: [vue()]
- })
你會發(fā)現(xiàn),Vue在這里被當做vite的一個內(nèi)置插件引入進來。剛才,我們說要局部引入Element Plus UI框架,我們打開Element Plus UI局部引入網(wǎng)址:(https://element-plus.gitee.io/#/zh-CN/component/quickstart),發(fā)現(xiàn)這里需要配置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 ---靜態(tài)文件夾
- components ---組件文件夾
- App.vue ---頁面文件
- main.ts ---項目入口文件
- shims-vue.d.ts ---類型定義文件(描述文件)
這么多文件,我們不一一展示了,主要看下App.vue、main.ts、shims-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的一個方法。為什么這里會使用它呢?引用官方的一句話:
- 從實現(xiàn)上看,defineComponent 只返回傳遞給它的對象。但是,就類型而言,返回的值有一個合成類型的構(gòu)造函數(shù),用于手動渲染函數(shù)、TSX 和 IDE 工具支持。
引入vue-router4
看完之前的基礎(chǔ)配置,我們現(xiàn)在準備開始引入Vue3的生態(tài)系統(tǒng)。
現(xiàn)在我們安裝 vue-router 版本的時候,默認還是安裝的 3.x 版本的,由于 vue3 的更新發(fā)生很大的變化,所以為了兼容處理,vue-router 也將發(fā)布最新版 4.x 版本了。
這是router4的官方網(wǎng)址:
- https://next.router.vuejs.org/
1. 安裝
- npm install vue-router@4
2. 配置文件
安裝完依賴后,在項目文件夾src下創(chuàng)建一個router文件夾,里面創(chuàng)建一個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文件夾下創(chuàng)建一個views文件夾,里面創(chuàng)建兩個頁面文件。分別是About.vue和Home.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這個構(gòu)建工具構(gòu)建的項目,所以我們只需要這樣。
- npm install -D sass
我們可以看到官方解釋:
- Vite 同時提供了對 .scss, .sass, .less, .styl 和 .stylus 文件的內(nèi)置支持。沒有必要為他們安裝特定的 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
我們在上面已經(jīng)成功配置局部引入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>
這里,你會發(fā)現(xiàn)引入了 vue-class-component這個組件,它是干什么的呢?
官方網(wǎng)址:
- https://class-component.vuejs.org/
- Vue Class Component is a library that lets you make your Vue components in class-style syntax.
譯:Vue類組件是一個庫,允許您以類樣式語法創(chuàng)建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自定義組件
我們經(jīng)常自己封裝組件,那么在這個項目中我們是怎樣引入的呢?我們在src目錄下創(chuàng)建一個components文件夾,里面創(chuàng)建一個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生態(tài)中肯定少不了vuex,為了兼容vue3,vuex也推出了4.0版本。
- https://next.vuex.vuejs.org/
你可以這樣安裝它。
- npm install vuex@next --save
你可以在src文件夾創(chuàng)建一個store文件夾,里面創(chuàng)建一個一個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");
結(jié)語
我們這里只是簡單地使用vite+ts+vue3搭建了一個小demo,如果你想更深層地使用它,可以關(guān)注我的動態(tài)。