Vue3項目搭建規范


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是一款強大的格式化工具

  1. 安裝開發式(-D)依賴prettier
    npm install prettier -D
  2. 配置.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
}
  1. 創建.prettierignore忽略文件
/dist/*
.local
.output.js
/node_modules/**

**/*.svg
**/*.sh

/public/*
  1. VSCode需要安裝prettier的插件:Prettier-Code formatter
  2. 在package.json中配置一個scripts
    "prettier": "prettier --write ."
  1. 執行腳本:
    npm run prettier

1.3 使用ESLint檢測

  1. VSCode安裝ESLint插件:ESLint
  2. 解決eslint和prettier沖突的問題
    npm i eslint-plugin-prettier eslint-config-prettier -D
  3. 添加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集成

  1. 安裝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集成

  1. 全局引用:所有組件全部集成

優點:集成簡單,方便使用
缺點:全部會打包

import ElementPlus from 'element-plus';
import 'element-plus/theme-chalk/index.css';
app.use(ElementPlus)
  1. 按需引用

優點:包會小一些
缺點:引用麻煩

<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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM