Vite 開發快速入門

一、Vite 簡介

================

Vite (法語意爲 "快速的",發音 /vit/) 是一種面向現代瀏覽器的一個更輕、更快的前端構建工具,能夠顯著提升前端的開發體驗。除了 Vite 外,前端著名的構建工具還有 Webpack 和 Gulp。目前,Vite 已經發布了 Vite2,Vite 全新的插件架構、絲滑的開發體驗,可以和 Vue3 的完美結合。

1.1 Vite 組成

Vite 構建工具由兩部分組成:

總的來說,Vite 希望提供開箱即用的配置,同時它的插件 API 和 JavaScript API 帶來了高度的可擴展性。不過,相比 Vue-cli 配置來說,Vite 構建的項目還是有很多的配置需要開發者自己進行處理。

1.2 瀏覽器支持

二、環境搭建

2.1 創建項目

根據 Vite 官網介紹,我們可以使用 npm 或 yarn 來初始化 Vite 項目,並且 Node.js 的版本需要 >= 12.0.0。

使用 NPM 方式

npm init vite@latest 項目名

使用 Yarn 方式

yarn create vite 項目名

除此之外,還可以通過附加的命令行選項直接指定項目名稱和模板。例如,要構建一個 Vite + Vue 項目,命令如下:

# npm 6.x
npm init @vitejs/app my-vue-app --template vue

# npm 7+, 需要額外的雙橫線:
npm init @vitejs/app my-vue-app -- --template vue

# yarn
yarn create @vitejs/app my-vue-app --template vue

輸入完命令之後,按照提示操作即可。如果項目需要支持 TypeScript,可以在初始化項目的時候選擇 vue-ts。項目創建好之後,可以發現 Vite 所創建好的項目其實與使用 Vue-cli 所創建的項目目錄結構其實是差不多的。

2.2 集成 Vue-Router

2.2.1 安裝配置 Vue-Router

Vue-Router 作爲大多數項目必不可少的路由工具,已經被大多數的前端項目所使用,Vue-Router 可以讓構建單頁面應用變得更加的容易。首先,在項目中安裝 Vue-Router,安裝命令如下:

//npm
npm install vue-router@next --save

//yarn
yarn add vue-router@next --save

安裝完成之後,在 src 目錄下創建一個文件夾 router/index.ts,然後添加如下一些配置:

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

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    { path: '/', component: () => import('views/home.vue') }
  ]
});

export default router

然後,我們在 main.ts 文件中引入 Vue-Router,如下所示。

import router from './router';
createApp(App).use(router).mount("#app");

2.2.2 新增路由頁面

爲了方便掩飾,我們再新增兩個路由頁面。熟悉,創建 pages 文件夾,把需要展示的頁面創建完成。然後,我們在 router/index.ts 註冊我們新增的頁面,如下所示。

routes: [
        {
            path: "/home",
            name: "Home",
            alias: "/",
            component: () => import("../pages/Home.vue")
        },
    ]

接下來,我們再修改一下 App.vue 的代碼,如下所示。

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

<script lang="ts">
import { defineComponent } from 'vue'

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

接下來啓動服務,就可以看到所配置的頁面了,並且點擊還能夠跳轉到對應的頁面。

2.3 集成 Vuex

Vuex 是一個專爲 Vue.js 應用程序開發的狀態管理模式。它採用集中式存儲管理應用的所有組件的狀態,並以相應的規則保證狀態以一種可預測的方式發生變化。Vuex 也集成到 Vue 的官方調試工具 devtools extension (opens new window),提供了諸如零配置的 time-travel 調試、狀態快照導入導出等高級調試功能。

使用 Vuex 之前,需要先安裝 Vuex 插件,如下所示。

//npm
npm install vuex@next --save

//yarn
yarn add vuex@next --save

安裝完成之後,需要先初始化 Vuex。首先,創建一個 store/index.ts 文件,添加如下代碼。

import { createStore } from "vuex";

const store = createStore({
  modules: {
    home: {
      namespaced: true,
      state: {
        count: 1
      },
      mutations: {
        add(state){
          state.count++;
        }
      }
    }
  }
})

export default store;

上面的代碼作用就是實現一個簡單的自加功能。然後,我們在 main.js 文件中引入 Vuex。

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

import store from "./store";

const app = createApp(App);
app.use(store);
app.mount('#app');

完成上述操作之後,接下來我們給 Vuex 編寫一個測試代碼看 Vuex 是否有效。修改 Home.vue 的代碼如下。

<template>
  <h1>Home Page</h1>
  <h2>{{count}}</h2>
  <button @click="handleClick">click</button>
</template>

<script lang="ts">
import { defineComponent, computed } from 'vue';
import { useStore } from 'vuex';

export default defineComponent({
  setup () {
    const store = useStore();
    const count = computed(() => store.state.home.count);
    const handleClick = () ={
      store.commit('home/add');
    };
    return {
      handleClick,
      count
    };
  }
})
</script>

上面的代碼實現的就是一個簡單的自加功能,和默認示例工程的效果事一樣的,只不過我們使用 Vuex。

2.4 集成 Eslint

ESLint 是一個用來識別 ECMAScript 語法, 並且按照規則給出報告的代碼檢測工具,使用它可以避免低級錯誤和統一代碼的風格。集成 Eslint 需要安裝如下一些插件:

npm 方式

npm install eslint -D
npm install eslint-plugin-vue -D
npm install @vue/eslint-config-typescript -D
npm install @typescript-eslint/parser -D
npm install @typescript-eslint/eslint-plugin -D
npm install typescript -D
npm install prettier -D
npm install eslint-plugin-prettier -D
npm install @vue/eslint-config-prettier -D

yarn 方式

yarn add eslint --dev
yarn add eslint-plugin-vue --dev
yarn add @vue/eslint-config-typescript --dev
yarn add @typescript-eslint/parser --dev
yarn add @typescript-eslint/eslint-plugin --dev
yarn add typescript --dev
yarn add prettier --dev
yarn add eslint-plugin-prettier --dev
yarn add @vue/eslint-config-prettier --dev

安裝完成之後,還需要根目錄下創建一個. eslintrc 文件,如下。

{
  "root": true,
  "env"{
    "browser": true,
    "node": true,
    "es2021"true
  },
  "extends"[
    "plugin:vue/vue3-recommended",
    "eslint:recommended",
    "@vue/typescript/recommended"
  ],
  "parserOptions"{
    "ecmaVersion"2021
  }
}

添加了配置規則之後,還需要在 package.json 文件的 scripts 中添加如下命令:

{
    "lint""eslint --ext src/**/*.{ts,vue} --no-error-on-unmatched-pattern"
}

接下來運行一下yarn lint就可以了,可以通過 eslint 完成格式的校驗了。不過,我們在執行yarn lint的時候會把所有的文件全部都校驗一次,如果有很多文件的話,那麼校驗起來速度將會很慢,此時,我們一般只在 git 提交的時候纔對修改的文件進行 eslint 校驗,那麼我們可以這麼做。
那就需要使用 lint-staged 插件。

//npm
npm install lint-staged -D
//yarn 
yarn add lint-staged --dev

然後,我們對 package.json 進行修改:

{
  "gitHooks"{
    "commit-msg""node scripts/commitMessage.js",
    "pre-commit""lint-staged"
  },
  "lint-staged"{
    "*.{ts,vue}""eslint --fix"
  },
  "scripts"{
    "test:unit""jest",
    "test:e2e""cypress open",
    "test""yarn test:unit && npx cypress run",
    "lint""npx prettier -w -u . && eslint --ext .ts,.vue src/** --no-error-on-unmatched-pattern",
    "bea""npx prettier -w -u ."   
  },
}

2.5 配置 alias


在過去使用 vue-cli 的時候,我們總是使用 @去引入某些文件,由於 Vite 沒有提供類似的配置,所以我們需要手動的對其進行相關配置,才能繼續使用 @符號去快捷的引入文件。首先,我們需要修改 vite.config.ts 的配置。

import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import { join } from "path";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: [
      {
        find: '@',
        replacement: '/src',
      },
      { find: 'views', replacement: '/src/views' },
      { find: 'components', replacement: '/src/components' },
    ]
  }
});

然後,我們在修改 tsconfig.json 文件,如下。

{
  "compilerOptions"{
    "target""esnext",
    "module""esnext",
    "moduleResolution""node",
    "strict": true,
    "jsx""preserve",
    "sourceMap": true,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "lib"["esnext""dom"],
   
   //以下爲需要添加內容
    "types"["vite/client""jest"],
    "baseUrl"".",
    "paths"{
      "@/*"["src/*"]
    } 
  },
  "include"[
    "src/**/*.ts",
    "src/**/*.d.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
  ]
}

2.6 集成 element-plus


Element Plus 是由餓了麼大前端團隊開源出品的一套爲開發者、設計師和產品經理準備的基於 Vue 3.0 的組件庫,可以幫助開發者快速的開發網站,如果你使用過 element-ui,那麼可以快速的過渡到 element-plus。除了 element-plus,支持 Vue 3.0 的 UI 框架還有很多。

首先,在項目的根目錄下安裝 element-plus,命令如下:

npm install element-plus --save

2.6.1 引入 element-plus

我們可以引入整個 element-plus,也可以根據需要僅引入部分組件。如果是全部引入,只需要在 main.js 添加如下代碼即可。

import { createApp } from 'vue'
import ElementPlus from 'element-plus';
i

const app = createApp(App)
app.use(ElementPlus)
app.mount('#app')

如果爲了減小項目的包體積,那麼只需要引入對應的功能組件即可。首先,安裝 babel-plugin-component 插件,如下所示。

npm install babel-plugin-component --save

然後,修改. babelrc 的配置內容。

{
  "plugins"[
    [
      "component",
      {
        "libraryName""element-plus",
        "styleLibraryName""theme-chalk"
      }
    ]
  ]
}

如果我們只需要引入部分組件,比如 Button 和 Select 組件,那麼需要在 main.js 中引入對應的組件即可,如下所示。

import { createApp } from 'vue'
import { store, key } from './store';
import router from "./router";
import { ElButton, ElSelect } from 'element-plus';
import App from './App.vue';
import './index.css'

const app = createApp(App)
app.component(ElButton.name, ElButton);
app.component(ElSelect.name, ElSelect);

/* 或者
 * app.use(ElButton)
 * app.use(ElSelect)
 */

app.use(store, key)
app.use(router)
app.mount('#app')

2.6.2 添加配置

引入 Element Plus 後,我們可以添加一個全局配置對象。該對象目前支持 size 與 zIndex 字段。size 用於改變組件的默認尺寸,zIndex 設置彈框的初始 z-index。以下是兩種不同的引入方式:

全局引入:

import { createApp } from 'vue'
import ElementPlus from 'element-plus';
import App from './App.vue';

const app = createApp(App)
app.use(ElementPlus, { size: 'small', zIndex: 3000 });

按需引入:

import { createApp } from 'vue'
import { ElButton } from 'element-plus';
import App from './App.vue';

const app = createApp(App)
app.config.globalProperties.$ELEMENT = option
app.use(ElButton);

2.6.3 配置 proxy 和 alias

如果要在 Vite 中使用 alias 別名配置和 proxy 代理配置,那麼需要在 vite.config.ts 文件中進行單獨的配置。

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

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    styleImport({
      libs: [
        {
          libraryName: 'element-plus',
          esModule: true,
          ensureStyleFile: true,
          resolveStyle: (name) ={
            return `element-plus/lib/theme-chalk/${name}.css`;
          },
          resolveComponent: (name) ={
            return `element-plus/lib/${name}`;
          },
        }
      ]
    })
  ],

  /**
   * 在生產中服務時的基本公共路徑。
   * @default '/'
   */
  base: './',
  /**
  * 與“根”相關的目錄,構建輸出將放在其中。如果目錄存在,它將在構建之前被刪除。
  * @default 'dist'
  */
  // outDir: 'dist',
  server: {
    // hostname: '0.0.0.0',
    host: "localhost",
    port: 3001,
    // // 是否自動在瀏覽器打開
    // open: true,
    // // 是否開啓 https
    // https: false,
    // // 服務端渲染
    // ssr: false,
    proxy: {
      '/api'{
        target: 'http://localhost:3333/',
        changeOrigin: true,
        ws: true,
        rewrite: (pathStr) => pathStr.replace('/api''')
      },
    },
  },
  resolve: {
    // 導入文件夾別名
    alias: {
      '@': path.resolve(__dirname, './src'),
      views: path.resolve(__dirname, './src/views'),
      components: path.resolve(__dirname, './src/components'),
      utils: path.resolve(__dirname, './src/utils'),
      less: path.resolve(__dirname, "./src/less"),
      assets: path.resolve(__dirname, "./src/assets"),
      com: path.resolve(__dirname, "./src/components"),
      store: path.resolve(__dirname, "./src/store"),
      mixins: path.resolve(__dirname, "./src/mixins")
    },
  }
})

其中,vite-plugin-style-import 是一個可以按需引入樣式的庫。

三、數據請求

Vue 本身是不支持 ajax 調用的,如果需要執行網絡請求,那麼就需要藉助一些工具,如 superagent 和 axios。不過,Vue 開發使用得比較多的還是 axios。

//npm
npm insall axios -save

//yarn 
yarn add axios -save

然後,新建一個 request.ts,添加如下的代碼。

import axios from 'axios';

let request = axios.create({
    baseURL: 'http://localhost:3555/api'
})

export default request;

然後,在新建一個 index.ts,用來處理具體的網絡請求,比如:

import request from "./axios";

export const getUrl = () ={
    return request({
        url: "/users/test" // 請求地址
    })
}

export default { getUrl };

最後,在我們的頁面代碼中調用上面定義的接口即可。

import { getUrl } from "../api/index"

export default {
    setup() {
        const getUrls = async() =>{
            const res = await getUrl()
            console.log(res)
        }
        onMounted(() ={ 
            getUrls()
        })
    }
}
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/b3m9zM3WVDIKAgzhSVNHEw