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
相关文章
|
4月前
|
JavaScript 前端开发 安全
Vue 3
Vue 3以组合式API、Proxy响应式系统和全面TypeScript支持,重构前端开发范式。性能优化与生态协同并进,兼顾易用性与工程化,引领Web开发迈向高效、可维护的新纪元。(238字)
723 139
|
4月前
|
缓存 JavaScript 算法
Vue 3性能优化
Vue 3 通过 Proxy 和编译优化提升性能,但仍需遵循最佳实践。合理使用 v-if、key、computed,避免深度监听,利用懒加载与虚拟列表,结合打包优化,方可充分发挥其性能优势。(239字)
371 1
|
5月前
|
开发工具 iOS开发 MacOS
基于Vite7.1+Vue3+Pinia3+ArcoDesign网页版webos后台模板
最新版研发vite7+vue3.5+pinia3+arco-design仿macos/windows风格网页版OS系统Vite-Vue3-WebOS。
560 11
|
4月前
|
JavaScript 安全
vue3使用ts传参教程
Vue 3结合TypeScript实现组件传参,提升类型安全与开发效率。涵盖Props、Emits、v-model双向绑定及useAttrs透传属性,建议明确声明类型,保障代码质量。
436 0
|
6月前
|
缓存 前端开发 大数据
虚拟列表在Vue3中的具体应用场景有哪些?
虚拟列表在 Vue3 中通过仅渲染可视区域内容,显著提升大数据列表性能,适用于 ERP 表格、聊天界面、社交媒体、阅读器、日历及树形结构等场景,结合 `vue-virtual-scroller` 等工具可实现高效滚动与交互体验。
622 1
|
6月前
|
缓存 JavaScript UED
除了循环引用,Vue3还有哪些常见的性能优化技巧?
除了循环引用,Vue3还有哪些常见的性能优化技巧?
355 0
|
7月前
|
JavaScript
vue3循环引用自已实现
当渲染大量数据列表时,使用虚拟列表只渲染可视区域的内容,显著减少 DOM 节点数量。
168 0
|
5月前
|
JavaScript
Vue中如何实现兄弟组件之间的通信
在Vue中,兄弟组件可通过父组件中转、事件总线、Vuex/Pinia或provide/inject实现通信。小型项目推荐父组件中转或事件总线,大型项目建议使用Pinia等状态管理工具,确保数据流清晰可控,避免内存泄漏。
481 2
|
4月前
|
缓存 JavaScript
vue中的keep-alive问题(2)
vue中的keep-alive问题(2)
407 137
|
8月前
|
人工智能 JavaScript 算法
Vue 中 key 属性的深入解析:改变 key 导致组件销毁与重建
Vue 中 key 属性的深入解析:改变 key 导致组件销毁与重建
940 0

热门文章

最新文章