使用 Vite2-TypeScript4-Vue3 技術棧,如何入手開發項目

前言

已經兩週沒有發文了,自己臨時有點事耽誤了,在這裏向大家表示深深地歉意。今天,我們使用 vite2.0+vue3+ts 來開發一個 demo 項目。

實戰

我們,打開 Vite 官方網站 (https://cn.vitejs.dev/)。

Vite (法語意爲 "快速的",發音 /vit/) 是一種新型前端構建工具,能夠顯著提升前端開發體驗。它主要由兩部分組成:
一個開發服務器,它基於 原生 ES 模塊 提供了 豐富的內建功能,如速度快到驚人的 模塊熱更新(HMR)。
一套構建指令,它使用 Rollup 打包你的代碼,並且它是預配置的,可以輸出用於生產環境的優化過的靜態資源。
Vite 意在提供開箱即用的配置,同時它的 插件 API 和 JavaScript API 帶來了高度的可擴展性,並有完整的類型支持。

這裏,我們將 Vite 與 VueCLI 做一下對比。

搭建項目

我們來搭建第一個 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"
  ]
}
  1. 配置 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
  1. 配置文件

安裝完依賴後,在項目文件夾 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,如果你想更深層地使用它,可以關注我的動態。

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/oTpIDKMCE2yVo0mAnN3dWQ