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