Vue3項目搭建規範
一. 代碼規範
1.1 內建editorconfig配置
EditorConfig有助于為不同IDE編輯器上維護一緻的編碼風格
安裝插件:EditorConfig for VS Code 後會讀取.editorconfig檔案
# http://editorconfig.org
root = true
[*] # 表示所有檔案适用
charset = utf-8 # 設定檔案字元集為 utf-8
indent_style = space # 縮進風格(tab | space)
indent_size = 2 # 縮進大小
end_of_line = lf # 控制換行類型(lf | cr | crlf)
trim_trailing_whitespace = true # 去除行首的任意空白字元
insert_final_newline = true # 始終在檔案末尾插入一個新行
[*.md] # 表示僅 md 檔案适用以下規則
max_line_length = off
trim_trailing_whitespace = false
1.2 使用prettier工具
Prettier是一款強大的格式化工具
- 安裝開發式(-D)依賴prettier
npm install prettier -D
- 配置.prettierrc檔案:
- useTabs:使用tab縮進還是空格縮進,選擇false;
- tabWidth:tab是空格的情況下,是幾個空格,選擇2個;
- printWidth:當行字元的長度,推薦80,也有人喜歡100或者120;
- singleQuote:使用單引号還是雙引号,選擇true,使用單引号;
- trailingComma:在多行輸入的尾逗号是否添加,設定為 none;
- semi:語句末尾是否要加分号,預設值true,選擇false表示不加;
{
"useTabs": false,
"tabWidth": 2,
"printWidth": 80,
"singleQuote": true,
"trailingComma": "none",
"semi": false
}
- 建立.prettierignore忽略檔案
/dist/*
.local
.output.js
/node_modules/**
**/*.svg
**/*.sh
/public/*
- VSCode需要安裝prettier的插件:
Prettier-Code formatter
- 在package.json中配置一個scripts
"prettier": "prettier --write ."
- 執行腳本:
npm run prettier
1.3 使用ESLint檢測
- VSCode安裝ESLint插件:
ESLint
- 解決eslint和prettier沖突的問題
npm i eslint-plugin-prettier eslint-config-prettier -D
- 添加prettier插件
extends: [
"plugin:vue/vue3-essential",
"eslint:recommended",
"@vue/typescript/recommended",
"@vue/prettier",
"@vue/prettier/@typescript-eslint",
'plugin:prettier/recommended'
],
二、項目搭建規範-第三方庫內建
2.1 vue.config.js配置(修改vue-cli封裝好的内部webpack)
node接受commonJS模闆規範
const path require('path')
module.exports = {
// 1. 配置方式一: CLI提供的屬性
outputDir: './build',
publicPath: './', // 打包後檔案是相對路徑
// 2. 配置方式二: 和Webpack屬性完全一緻,最後會進行合并
configureWebpack: {
resolve: {
alias: {
components: '@/components'
}
}
},
// configure是函數形式:直接覆寫原Webpack配置
configureWebpack: (config) => {
config.resolve.alias = {
"@": path.resolve(__dirname, 'src'),
components: '@/components'
}
},
// 3. 配置方式三:chainWebpack鍊式形式
chainWebpack: (config) => {
config.resolve.alias.set('@', path.resolve(__dirname, 'src').set('components', '@/components'))
}
}
2.2 vue-router內建
- 安裝vue-router最新版本
npm install vue-router@next
defineComponent
:定義元件,更好的支援ts
2. 建立router對象
import { createRouter, createWebHashHistory } from 'vue-router';
import type { RouteRecordRaw } from 'vue-router'; // 聲明導入的是一個type,可不加
const routes: RouteRecordRaw[] = [
{
path: '/',
redirect: '/login'
},
{
path: '/login',
component: () => import('@/views/login/index.vue')
},
{
path: '/main',
component: () => import('@/views/main/index.vue')
}
]
const router = createRouter({
routes,
history: createWebHashHistory()
})
export default router
2.3 element-plus內建
- 全局引用:所有元件全部內建
優點:內建簡單,友善使用
缺點:全部會打包
import ElementPlus from 'element-plus';
import 'element-plus/theme-chalk/index.css';
app.use(ElementPlus)
- 按需引用
優點:包會小一些
缺點:引用麻煩
<el-button type="primary">哈哈哈哈</el-button>
import { ElButton } from 'element-plus'
import 'element-plus/theme-chalk/base.css';
import 'element-plus/theme-chalk/el-button.css';
components: {
ElButton
}
以上方法太麻煩,可以添加babel-plugin-import工具進行按需引入,并進行配置
npm install babel-plugin-import -D
// babel.config.js
module.exports = {
plugins: [
[
'import',
{
libraryName: 'element-plus',
// 引入元件
customName: (name) => {
name = name.slice(3)
return `element-plus/lib/components/${name}`
},
// 引入樣式
customStyleName: (name) => {
name = name.slice(3)
// 如果你需要引入 [name].scss 檔案,你需要用下面這行
// return `element-plus/lib/components/${name}/style`
// 引入 [name].css
return `element-plus/lib/components/${name}/style/css`
}
}
]
],
presets: ['@vue/cli-plugin-babel/preset']
}
- main.ts入口檔案存放主要邏輯
- 把共性的邏輯進行抽取
// main.ts
import { createApp, App } from 'vue'
import { globalRegister } from './global'
import rootApp from './App.vue'
const app: App = createApp(rootApp)
/** app.use()有傳入函數的兩種方式
app.use(function(app: App) {
})
app.use({
install: function(app: App) {
}
})
*/
// 方式一:
globalRegister(app)
// 方式二:更優雅
app.use(globalRegister)
// global/index.ts
import { App } from 'vue'
import registerElement from './regiserElement'
export function globalRegister(app: App): void {
registerElement(app)
}
// global/registerELement
import { App } from 'vue'
import 'element-plus/theme-chalk/base.css';
import { ElButton, ElForm } from 'element-plus'
const components = [
ElButton,
ElForm
]
export default function (app: App): void {
for (const component of components) {
app.component(component.name, component)
}
}
三、其他檔案
1. .browserslistrc - 幫助我們做浏覽器适配
- 幫助我們做浏覽器适配
- css查詢檔案
- babel:ES6 TS -> JS
> 1% // 市場佔有率大于百分之一的浏覽器
last 2 versions // 适配主流浏覽器的最新的兩個版本
not dead // 目前浏覽器處于維護狀态的
2. tsconfig.json - TS配置檔案
{
"compilerOptions": { // 編譯選項
// 目标代碼(ts -> js(es5/6/7))
"target": "esnext",
// 目标代碼需要使用的子產品化方案(commonjs require/module.exports/es module import/export),常寫umd,代表支援多種子產品化
"module": "esnext",
// 嚴格的檢查(any)
"strict": true,
// 對jsx進行怎樣的處理,不轉化preserve保留
"jsx": "preserve",
// 輔助導入功能
"importHelpers": true,
// 按照node方式去解析子產品 import "/index.node .json .js"
"moduleResolution": "node",
// 跳過一些庫的類型檢測(axios本身會定義很多類型,提高性能,有可能多個庫的類型命名會沖突)
"skipLibCheck": true,
// export default/module.exports = {}是否能混合使用
// es module / commonjs 是否能混合使用
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
// 要不要生成映射檔案(ts -> js)
"sourceMap": true,
// 檔案路徑在解析時的基本的url
"baseUrl": ".",
// 指定具體要解析使用的類型,不傳時target寫的什麼類型在這裡就可以使用
"types": ["webpack-env"],
// 編譯的路徑解析,使用@/components會在src/components中尋找
"paths": {
"@/*": ["src/*"],
"components/*": ["src/components/*"] // (我們自己新增的)
},
// 可以指定在項目中可以使用哪些庫的類型(Proxy/Window/Document)
"lib": ["esnext", "dom", "dom.iterable", "scripthost"]
},
// 哪些檔案需要被限制和解析
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"tests/**/*.ts",
"tests/**/*.tsx"
],
// 排除哪些檔案被限制和解析
"exclude": ["node_modules"]
}
3. shims-vue.d.ts 聲明,防止報錯
declare module '*.vue' {
import type { DefineComponent } from 'vue'
const component: DefineComponent<{}, {}, any>
export default component
}
// 聲明一下$store,防止報錯
declare let $store: any