Vue3+TS+Vite+NaiveUI搭建一個項目骨架

語言: CN / TW / HK

theme: fancy highlight: atom-one-light


持續創作,加速成長!這是我參與「掘金日新計劃 · 6 月更文挑戰」的第22天,點擊查看活動詳情

Hi~,我是一碗周,如果寫的文章有幸可以得到你的青睞,萬分有幸~

🍈 寫在前面

現在已經有很多項目團隊使用Vue3+TS進行開發,同時也就意味着Vue3的生態越來越完善,如果還是停留在Vue2的階段已經out了,這篇文章將會使用Vue3+TS+NaivaUI搭建一個簡單的項目骨架。

🍊 創建Vue3項目

首先我們通過Vite來創建一個Vue3+TS的一個項目,打開終端,找到我們項目應該存放的目錄,出書如下命令:

```powershell npm create vite@latest

```

如果你是第一次使用Vite,需要先輸入y,然後回依次出現:

  • 項目名稱(想叫什麼叫什麼)

  • 框架(這裏選擇的是Vue)

  • Variant(這裏選擇的是Vue3+TS)

鍵入回車後等待一會項目就創建好了,然後進入項目安裝依賴就好。

🍉 開發規範

這裏對開發規範的配置僅配置ESLint,其他的StyleLint、git提交驗證這裏不進行介紹;這裏還會安裝Prettier,用於代碼格式化。

首先安裝依賴:

powershell npm i -D eslint eslint-plugin-vue eslint-define-config # eslink npm i -D prettier eslint-plugin-prettier @vue/eslint-config-prettier # prettire npm i -D @vue/eslint-config-typescript @typescript-eslint/eslint-plugin @typescript-eslint/parser # 對ts的支持

然後我們依次編寫一下對應的配置文件:

ESLint風格檢查配置文件:.eslintrc.js

```javascript const { defineConfig } = require('eslint-define-config')

module.exports = defineConfig({ root: true, / 指定如何解析語法。/ parser: 'vue-eslint-parser', / 優先級低於parse的語法解析配置 / parserOptions: { parser: '@typescript-eslint/parser', //模塊化方案 sourceType: 'module', }, env: { browser: true, es2021: true, node: true, // 解決 defineProps and defineEmits generate no-undef warnings 'vue/setup-compiler-macros': true, }, // http://eslint.bootcss.com/docs/user-guide/configuring#specifying-globals globals: {}, extends: [ 'plugin:vue/vue3-recommended', 'eslint:recommended', 'plugin:@typescript-eslint/recommended', // typescript-eslint推薦規則, 'prettier', 'plugin:prettier/recommended', ], // http://cn.eslint.org/docs/rules/ rules: { // 禁止使用 var 'no-var': 'error', semi: 'off', // 優先使用 interface 而不是 type '@typescript-eslint/consistent-type-definitions': ['error', 'interface'], '@typescript-eslint/no-explicit-any': 'off', // 可以使用 any 類型 '@typescript-eslint/explicit-module-boundary-types': 'off', // 解決使用 require() Require statement not part of import statement. 的問題 '@typescript-eslint/no-var-requires': 0, // http://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/ban-types.md '@typescript-eslint/ban-types': [ 'error', { types: { // add a custom message to help explain why not to use it Foo: "Don't use Foo because it is unsafe",

      // add a custom message, AND tell the plugin how to fix it
      String: {
        message: 'Use string instead',
        fixWith: 'string',
      },

      '{}': {
        message: 'Use object instead',
        fixWith: 'object',
      },
    },
  },
],
// 禁止出現未使用的變量
'@typescript-eslint/no-unused-vars': [
  'error',
  { vars: 'all', args: 'after-used', ignoreRestSiblings: false },
],
'prettier/prettier': [
  'error',
  { singleQuote: true, parser: 'flow', semi: false },
],
'vue/html-indent': 'off',
// 關閉此規則 使用 prettier 的格式化規則,
'vue/max-attributes-per-line': ['off'],
// 優先使用駝峯,element 組件除外
'vue/component-name-in-template-casing': [
  'error',
  'PascalCase',
  {
    ignores: ['/^el-/', '/^router-/'],
    registeredComponentsOnly: false,
  },
],
// 強制使用駝峯
camelcase: ['error', { properties: 'always' }],
// 優先使用 const
'prefer-const': [
  'error',
  {
    destructuring: 'any',
    ignoreReadBeforeAssign: false,
  },
],

}, })

```

Prettier的代碼格式化配置文件:prettierrc.js

```javascript module.exports = { // 結尾分號 semi: false, // 單引號 singleQuote: true, // 一行80字符 printWidth: 80, // 尾逗號 trailingComma: 'all', // 箭頭函數的括號 arrowParens: 'avoid', // 換行符 endOfLine: 'lf', }

```

配置ESLint的代碼檢測忽略的文件的配置文件:.eslintignore

text /node_modules/ /public/ .vscode .idea

🍌 Vite配置

🍍 別名配置

配置別名可以幫助我們快速的找到我們想要的組件、圖片等內容,不用使用../../../的方式,首先配置vite.config.ts,通過resolve.alias的方式配置,示例代碼如下:

```typescript import { defineConfig } from 'vite' import type { ConfigEnv } from 'vite' import vue from '@vitejs/plugin-vue' import { resolve } from 'path'

// http://vitejs.dev/config/ export default defineConfig(({ mode }: ConfigEnv) => { return { resolve: { alias: { '/@': resolve(__dirname, 'src'), }, extensions: ['.js', '.json', '.ts', '.vue'], // 使用路徑別名時想要省略的後綴名,可以自己 增減 },

/* more config */
plugins: [vue()],

} })

```

這裏配置一個/@的別名,它指向src目錄,然後配置tsconfig.json,允許別名在使用,代碼如下:

json "compilerOptions": { // 用於設置解析非相對模塊名稱的基本目錄,相對模塊不會受到baseUrl的影響 "baseUrl": ".", "paths": { // 用於設置模塊名到基於baseUrl的路徑映射 "/@/*": [ "src/*" ], } },

🥭 環境變量

🍎 .env文件

在Vite中通過.env開頭的文件去讀取配置,來作為環境變量,Vite默認允許我們使用以下文件:

bash .env # 所有情況下都會加載 .env.local # 所有情況下都會加載,但會被 git 忽略 .env.[mode] # 只在指定模式下加載 .env.[mode].local # 只在指定模式下加載,但會被 git 忽略

這些文件是有優先級的,他們的優先級是.env<.env.local<.env.[mode]<.env.[mode].local;Vite中還預設了一些環境變量,這些的優先級是最高的,不會被覆蓋,分別如下:

  • MODE: {string}:應用運行的模式(開發環境下為development,生成環境為production)。

  • BASE_URL: {string}:部署應用時的基本 URL。他由base 配置項決定。

  • PROD: {boolean}:當前是否是生產環境。

  • DEV: {boolean}:當前是否是開發環境 (永遠與 PROD相反)。

這些環境變量Vite允許我們通過import.meto.env方式獲取。

🍏 定義環境變量

如果我麼你想要自定義環境變量,就必須以VITE_開頭,如果修改則需要通過envPrefix配置項,該配置項允許我們傳入一個非空的字符串作為變量的前置。

.env

bash VITE_APP_API_BASE_URL=http://127.0.0.1:8080/

定義完成之後我們就可以在項目中通過import.meta.env.VITE_APP_API_BASE_URL的方式獲取。

如果想要獲得TypeScript的類型提示,需要在創建一個src/type/env.d.ts(把原src目錄下的env.d.ts刪除),示例代碼如下:

```typescript ///

interface ImportMetaEnv { readonly VITE_APP_API_BASE_URL: string // 定義更多環境變量 }

interface ImportMeta { readonly env: ImportMetaEnv }

declare module '*.vue' { import type { DefineComponent } from 'vue' // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/ban-types const component: DefineComponent<{}, {}, any> export default component }

```

在使用時就會獲得智能提示。

🍑 在vite.config.ts中獲取環境變量

如果我們想要在vite.config.ts中獲取環境變量,需要使用Vite提供的loadEnv()方法,該方法的定義如下:

typescript function loadEnv( mode: string, envDir: string, prefixes?: string | string[] ): Record<string, string>

上面的三個參數的解釋如下:

  • mode:模式;

  • envDir:環境變量配置文件所在目錄;

  • prefixes:【可選】接受的環境變量前綴,默認為VITE_

瞭解了使用的API,在vite.config.ts中獲取環境變量示例代碼如下:

```typescript import { defineConfig, loadEnv } from 'vite' import vue from '@vitejs/plugin-vue' import AutoImport from 'unplugin-auto-import/vite' import Components from 'unplugin-vue-components/vite' import { ElementPlusResolver } from 'unplugin-vue-components/resolvers' import type { ConfigEnv } from 'vite'

// http://vitejs.dev/config/ export default defineConfig(({ mode }: ConfigEnv) => { const env = loadEnv(mode, process.cwd()) return { / more config / server: { proxy: { '/api': { target: env.VITE_APP_API_BASE_URL, changeOrigin: true, rewrite: path => path.replace(/^\/api/, ''), }, }, }, } })

```

🍒 自動導入

在使用setup語法糖進行開發的過程中,一些常用的API比如watchref等,需要每次都進行導入,而且組件如果是按需導入的話也需要進行導入,我們可以通過Vite的插件來幫助我們實現自動導入:

  • unplugin-vue-components:組件按需導入;

  • unplugin-auto-importvue, vue-router, vue-i18n, @vueuse/head, @vueuse/core等自動導入;

安裝命令如下:

powershell npm i -D unplugin-vue-components unplugin-auto-import

然後在vite.config.ts中導入並配置:

```typescript import { defineConfig, loadEnv } from 'vite' import type { ConfigEnv } from 'vite' import vue from '@vitejs/plugin-vue' import { resolve } from 'path' import AutoImport from 'unplugin-auto-import/vite' import Components from 'unplugin-vue-components/vite'

// http://vitejs.dev/config/ export default defineConfig(({ mode }: ConfigEnv) => { const env = loadEnv(mode, process.cwd()) return { resolve: { alias: { '/@': resolve(__dirname, 'src'), }, extensions: ['.js', '.json', '.ts', '.vue'], // 使用路徑別名時想要省略的後綴名,可以自己 增減 },

/* more config */
plugins: [
  vue(),
  AutoImport({
    resolvers: [],
    // 自定引入 Vue VueRouter API,如果還需要其他的可以自行引入
    imports: ['vue', 'vue-router'],
    // 調整自動引入的文件位置
    dts: 'src/type/auto-import.d.ts',
    // 解決自動引入eslint報錯問題 需要在eslintrc的extend選項中引入
    eslintrc: {
      enabled: true,
      // 配置文件的位置
      filepath: './.eslintrc-auto-import.json',
      globalsPropValue: true,
    },
  }),
  Components({
    resolvers: [
      // 需要自動導入的組件
    ],
    dts: 'src/type/components.d.ts',
  }),
],

} })

```

現在我們可以在項目中直接使用Vue和VueRouter的所有API。

但是現在還有一個問題就是ESLint對自動引入的API報錯,解決辦法如下:

```typescript // 在.eslintrc.js中的extends配置項加入'./.eslintrc-auto-import.json', extends: [ 'plugin:vue/vue3-recommended', 'eslint:recommended', 'plugin:@typescript-eslint/recommended', // typescript-eslint推薦規則, 'prettier', 'plugin:prettier/recommended', './.eslintrc-auto-import.json', ],

```

🍋 NaiveUI的安裝

Q:眾多UI組件庫這裏為什麼選擇NaiveUI?

A1:NaiveUI的官方文檔對於其他UI組件庫來説生動有趣;

A2:尤大推薦過;

A3:組件數量龐大;

安裝依賴命令如下:

powershell npm i -D naive-ui @vicons/ionicons5 # @vicons/ionicons5是icon的庫

配置NaiveUI自動導入功能,打開vite.config.ts,從unplugin-vue-components/resolvers中引入NaiveUiResolver,並添加的在plugin中,示例代碼如下:

typescript Components({ resolvers: [ // 需要自動導入的組件 NaiveUiResolver() ], dts: 'src/type/components.d.ts', }),

現在就已經把 NaiveUI安裝並引入了,其實很簡單。

現在我們來使用一下這個UI組件庫,這裏就直接在App.vue中編寫了,示例代碼如下:

```vue

```

在裏面展示了一部分組件,運行效果如下:

naive.gif

🍓 寫在最後

這篇文章到這裏就結束了,其實還有好多東西沒有安裝和配置,比如VueRouter、Pinia,還可以安裝TailWindCSS,這些依賴的安裝方式比較簡單,官網都有比較完整的安裝方式,這裏就不囉嗦了。