Vue3+TS+Vite+NaiveUI搭建一個項目骨架實現(xiàn)
?? 寫在前面
現(xiàn)在已經(jīng)有很多項目團隊使用Vue3+TS進行開發(fā),同時也就意味著Vue3的生態(tài)越來越完善,如果還是停留在Vue2的階段已經(jīng)out了,這篇文章將會使用Vue3+TS+NaivaUI搭建一個簡單的項目骨架。
?? 創(chuàng)建Vue3項目
首先我們通過Vite來創(chuàng)建一個Vue3+TS的一個項目,打開終端,找到我們項目應(yīng)該存放的目錄,出書如下命令:
npm create vite@latest
如果你是第一次使用Vite,需要先輸入y
,然后回依次出現(xiàn):
項目名稱(想叫什么叫什么)
框架(這里選擇的是Vue)
Variant(這里選擇的是Vue3+TS)
鍵入回車后等待一會項目就創(chuàng)建好了,然后進入項目安裝依賴就好。
?? 開發(fā)規(guī)范
這里對開發(fā)規(guī)范的配置僅配置ESLint,其他的StyleLint、git提交驗證這里不進行介紹;這里還會安裝Prettier,用于代碼格式化。
首先安裝依賴:
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的支持
然后我們依次編寫一下對應(yīng)的配置文件:
ESLint風格檢查配置文件:.eslintrc.js
const { defineConfig } = require('eslint-define-config') module.exports = defineConfig({ root: true, /* 指定如何解析語法。*/ parser: 'vue-eslint-parser', /* 優(yōu)先級低于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, }, // https://eslint.bootcss.com/docs/user-guide/configuring#specifying-globals globals: {}, extends: [ 'plugin:vue/vue3-recommended', 'eslint:recommended', 'plugin:@typescript-eslint/recommended', // typescript-eslint推薦規(guī)則, 'prettier', 'plugin:prettier/recommended', ], // https://cn.eslint.org/docs/rules/ rules: { // 禁止使用 var 'no-var': 'error', semi: 'off', // 優(yōu)先使用 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, // https://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', }, }, }, ], // 禁止出現(xiàn)未使用的變量 '@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', // 關(guān)閉此規(guī)則 使用 prettier 的格式化規(guī)則, 'vue/max-attributes-per-line': ['off'], // 優(yōu)先使用駝峰,element 組件除外 'vue/component-name-in-template-casing': [ 'error', 'PascalCase', { ignores: ['/^el-/', '/^router-/'], registeredComponentsOnly: false, }, ], // 強制使用駝峰 camelcase: ['error', { properties: 'always' }], // 優(yōu)先使用 const 'prefer-const': [ 'error', { destructuring: 'any', ignoreReadBeforeAssign: false, }, ], }, })
Prettier的代碼格式化配置文件:prettierrc.js
module.exports = { // 結(jié)尾分號 semi: false, // 單引號 singleQuote: true, // 一行80字符 printWidth: 80, // 尾逗號 trailingComma: 'all', // 箭頭函數(shù)的括號 arrowParens: 'avoid', // 換行符 endOfLine: 'lf', }
配置ESLint的代碼檢測忽略的文件的配置文件:.eslintignore
/node_modules/ /public/ .vscode .idea
?? Vite配置
?? 別名配置
配置別名可以幫助我們快速的找到我們想要的組件、圖片等內(nèi)容,不用使用../../../
的方式,首先配置vite.config.ts
,通過resolve.alias
的方式配置,示例代碼如下:
import { defineConfig } from 'vite' import type { ConfigEnv } from 'vite' import vue from '@vitejs/plugin-vue' import { resolve } from 'path' // https://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
,允許別名在使用,代碼如下:
"compilerOptions": { // 用于設(shè)置解析非相對模塊名稱的基本目錄,相對模塊不會受到baseUrl的影響 "baseUrl": ".", "paths": { // 用于設(shè)置模塊名到基于baseUrl的路徑映射 "/@/*": [ "src/*" ], } },
環(huán)境變量
?? .env文件
在Vite中通過.env開頭的文件去讀取配置,來作為環(huán)境變量,Vite默認允許我們使用以下文件:
.env # 所有情況下都會加載 .env.local # 所有情況下都會加載,但會被 git 忽略 .env.[mode] # 只在指定模式下加載 .env.[mode].local # 只在指定模式下加載,但會被 git 忽略
這些文件是有優(yōu)先級的,他們的優(yōu)先級是.env
<.env.local
<.env.[mode]
<.env.[mode].local
;Vite中還預(yù)設(shè)了一些環(huán)境變量,這些的優(yōu)先級是最高的,不會被覆蓋,分別如下:
MODE: {string}
:應(yīng)用運行的模式(開發(fā)環(huán)境下為development
,生成環(huán)境為production
)。BASE_URL: {string}
:部署應(yīng)用時的基本 URL。他由base
配置項決定。PROD: {boolean}
:當前是否是生產(chǎn)環(huán)境。DEV: {boolean}
:當前是否是開發(fā)環(huán)境 (永遠與PROD
相反)。
這些環(huán)境變量Vite允許我們通過import.meto.env
方式獲取。
?? 定義環(huán)境變量
如果我么你想要自定義環(huán)境變量,就必須以VITE_
開頭,如果修改則需要通過envPrefix配置項,該配置項允許我們傳入一個非空的字符串作為變量的前置。
.env
VITE_APP_API_BASE_URL=http://127.0.0.1:8080/
定義完成之后我們就可以在項目中通過import.meta.env.VITE_APP_API_BASE_URL
的方式獲取。
如果想要獲得TypeScript的類型提示,需要在創(chuàng)建一個src/type/env.d.ts
(把原src目錄下的env.d.ts
刪除),示例代碼如下:
/// <reference types="vite/client" /> interface ImportMetaEnv { readonly VITE_APP_API_BASE_URL: string // 定義更多環(huán)境變量 } 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中獲取環(huán)境變量
如果我們想要在vite.config.ts
中獲取環(huán)境變量,需要使用Vite提供的loadEnv()
方法,該方法的定義如下:
function loadEnv( mode: string, envDir: string, prefixes?: string | string[] ): Record<string, string>
上面的三個參數(shù)的解釋如下:
mode
:模式;envDir
:環(huán)境變量配置文件所在目錄;prefixes
:【可選】接受的環(huán)境變量前綴,默認為VITE_
。
了解了使用的API,在vite.config.ts
中獲取環(huán)境變量示例代碼如下:
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' // https://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/, ''), }, }, }, } })
?? 自動導(dǎo)入
在使用setup
語法糖進行開發(fā)的過程中,一些常用的API比如watch
、ref
等,需要每次都進行導(dǎo)入,而且組件如果是按需導(dǎo)入的話也需要進行導(dǎo)入,我們可以通過Vite的插件來幫助我們實現(xiàn)自動導(dǎo)入:
unplugin-vue-components
:組件按需導(dǎo)入;unplugin-auto-import
:vue, vue-router, vue-i18n, @vueuse/head, @vueuse/core
等自動導(dǎo)入;
安裝命令如下:
npm i -D unplugin-vue-components unplugin-auto-import
然后在vite.config.ts
中導(dǎo)入并配置:
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' // https://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'], // 調(diào)整自動引入的文件位置 dts: 'src/type/auto-import.d.ts', // 解決自動引入eslint報錯問題 需要在eslintrc的extend選項中引入 eslintrc: { enabled: true, // 配置文件的位置 filepath: './.eslintrc-auto-import.json', globalsPropValue: true, }, }), Components({ resolvers: [ // 需要自動導(dǎo)入的組件 ], dts: 'src/type/components.d.ts', }), ], } })
現(xiàn)在我們可以在項目中直接使用Vue和VueRouter的所有API。
但是現(xiàn)在還有一個問題就是ESLint對自動引入的API報錯,解決辦法如下:
// 在.eslintrc.js中的extends配置項加入'./.eslintrc-auto-import.json', extends: [ 'plugin:vue/vue3-recommended', 'eslint:recommended', 'plugin:@typescript-eslint/recommended', // typescript-eslint推薦規(guī)則, 'prettier', 'plugin:prettier/recommended', './.eslintrc-auto-import.json', ],
NaiveUI的安裝
Q:眾多UI組件庫這里為什么選擇NaiveUI?
A1:NaiveUI的官方文檔對于其他UI組件庫來說生動有趣;
A2:尤大推薦過;
A3:組件數(shù)量龐大;
安裝依賴命令如下:
npm i -D naive-ui @vicons/ionicons5 # @vicons/ionicons5是icon的庫
配置NaiveUI自動導(dǎo)入功能,打開vite.config.ts
,從unplugin-vue-components/resolvers
中引入NaiveUiResolver
,并添加的在plugin
中,示例代碼如下:
Components({ resolvers: [ // 需要自動導(dǎo)入的組件 NaiveUiResolver() ], dts: 'src/type/components.d.ts', }),
現(xiàn)在就已經(jīng)把 NaiveUI安裝并引入了,其實很簡單。
現(xiàn)在我們來使用一下這個UI組件庫,這里就直接在App.vue
中編寫了,示例代碼如下:
<script setup lang="ts"> import { zhCN, zhTW, dateZhCN, dateZhTW, darkTheme, lightTheme } from 'naive-ui' import { Sunny, Moon } from '@vicons/ionicons5' type LocaleType = 'zhCN' | 'zhTW' const locale = ref<LocaleType>('zhCN') const isDark = ref(false) const langOpt = [ { label: '簡體中文', key: 'zhCN' }, { label: '繁體中文', key: 'zhTW' }, ] const langList = { zhCN: { locale: zhCN, label: '簡體中文', dataLocale: dateZhCN }, zhTW: { locale: zhTW, label: '繁體中文', dataLocale: dateZhTW }, } const handleSelect = (e: LocaleType) => { locale.value = e } </script> <template> <NConfigProvider :locale="langList[locale].locale" :date-locale="langList[locale].dataLocale" :theme="isDark === true ? darkTheme : lightTheme" > <NGlobalStyle /> <!-- vue-router占位 --> <router-view/> </NConfigProvider> </template> <style></style>
在里面展示了一部分組件,運行效果如下:
?? 寫在最后
這篇文章到這里就結(jié)束了,其實還有好多東西沒有安裝和配置,比如VueRouter、Pinia,還可以安裝TailWindCSS,這些依賴的安裝方式比較簡單,官網(wǎng)都有比較完整的安裝方式,這里就不啰嗦了。
到此這篇關(guān)于Vue3+TS+Vite+NaiveUI搭建一個項目骨架實現(xiàn)的文章就介紹到這了,更多相關(guān)Vue3搭建項目骨架內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 如何搭建一個完整的Vue3.0+ts的項目步驟
- vite+vue3.0+ts+element-plus快速搭建項目的實現(xiàn)
- Vue3+script setup+ts+Vite+Volar搭建項目
- 一個基于vue3+ts+vite項目搭建初探
- 從零搭建一個vite+vue3+ts規(guī)范基礎(chǔ)項目(搭建過程問題小結(jié))
- 一步步帶你用vite簡單搭建ts+vue3全家桶
- 如何使用Vue3+Vite+TS快速搭建一套實用的腳手架
- 使用Vite搭建vue3+TS項目的實現(xiàn)步驟
- vue3+ts+vite+electron搭建桌面應(yīng)用的過程
- vue3+ts項目搭建的實現(xiàn)示例
相關(guān)文章
vue使用高德地圖實現(xiàn)實時定位天氣預(yù)報功能
這篇文章主要介紹了vue使用高德地圖實現(xiàn)實時天氣預(yù)報功能,根據(jù)定位功能,使用高德地圖實現(xiàn)定位當前城市的天氣預(yù)報功能,本文通過實例代碼給大家介紹的非常詳細,需要的朋友可以參考下2022-05-05Vue 報錯Error: No PostCSS Config foun
這篇文章主要介紹了Vue 報錯Error: No PostCSS Config found問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07