Skip to content

Vite创建项目

bash
 pnpm create vite
 pnpm i # 安装依赖
 pnpm dev # 启动

其他配置

  • Vue-Router
  • Pinia
  • ESLint
  • Prettier
  • JSX

修改vite.config.ts配置

typescript
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'

export default defineConfig({
  plugins: [vue()],
  resolve: {
    // 配置alias
    alias: {
      '@': resolve(__dirname, 'src') // 设置 `@` 指向 `src` 目录
    }
  }
})

server配置跨域等

typescript
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src') // 设置 `@` 指向 `src` 目录
    }
  },
  server: {
    port: 8080,
    open: true, // 服务器启动时是否自动打开浏览器
    // 配置代理服务,跨域请求
    proxy: {
      // 字符串写法 http://localhost:5173/api  => http://localhost:3000/api
      '/api': 'http://localhost:3000',
      // 带选项写法:http://localhost:5173/api/bar -> http://jsonplaceholder.typicode.com/bar
      '/api': {
        target: 'http://jsonplaceholder.typicode.com',
        changeOrigin: true,
        rewrite: path => path.replace(/^\/api/, '')
      }
    },
    cors: true // 是否启用CORS
  }
})

解释proxy

typescript
proxy: {
  '/api': 'http://localhost:3000'
}

当在前端代码中发起一个以 /api 开头的请求时,比如 /api/user,这个请求会被开发服务器转发(也称为代理)到 http://localhost:3000 这个地址上,最终的请求地址会变成 http://localhost:3000/api/user

规范目录结构

typescript
├── publish/
└── src/
    ├── assets/                    // 静态资源目录
    ├── common/                    // 通用类库目录
    ├── components/                // 公共组件目录
    ├── router/                    // 路由配置目录
    ├── store/                     // 状态管理目录
    ├── style/                     // 通用 CSS 目录
    ├── utils/                     // 工具函数目录
    ├── views/                     // 页面组件目录
    ├── App.vue
    ├── main.ts
    ├── shims-vue.d.ts
├── tests/                         // 单元测试目录
├── index.html
├── tsconfig.json                  // TypeScript 配置文件
├── vite.config.ts                 // Vite 配置文件
└── package.json

//  styles 或者 stores 单复数都可以,看心情

集成prettier配置

安装 Prettier

Install · Prettier

bash
pnpm i prettier -D
# 或者

# --save-exact 表示安装某个精确的版本
pnpm add --save-dev --save-exact prettier

Prettier配置

.prettierrc 是 Prettier 的配置文件,可以用来自定义代码格式化的规则。主要的配置属性有以下这些:

  • printWidth:一行的字符数,如果超过会进行折行,默认值是 80。
  • tabWidth:一个 tab 等于几个空格数,默认值是 2。
  • useTabs:是否使用 tab 进行缩进,默认值是 false,表示用空格进行缩进。
  • semi:是否在语句末尾打印分号,默认值是 true。
  • singleQuote:是否使用单引号,默认值是 false。
  • trailingComma:是否使用尾逗号,有三个可选值,"none","es5","all",默认值是 "none" ,表示不使用尾逗号。
  • bracketSpacing:对象大括号直接是否有空格,默认值是 true,效果:{ foo: bar }。
  • arrowParens:箭头函数参数是否使用括号,默认值是 "avoid",表示尽可能省略括号,如 (x) => x 将被格式化为 x => x。
typescript
{
  "semi": false,
  "singleQuote": true,
  "arrowParens": "always",
  "trailingComma": "none"
}
typescript
{
  printWidth: 120, // 一行的字符数,如果超过会进行折行,默认值是 80。
  tabWidth: 2, // 一个 tab 等于几个空格数,默认值是 2。
  useTabs: false, // 是否使用 tab 进行缩进,默认值是 false,表示用空格进行缩进。
  semi: false, // 句末是否加分号
  singleQuote: true, // 用单引号
  trailingComma: 'none', // 最后一个对象元素是否加逗号
  bracketSpacing: true, // 对象,数组对象大括号直接是否有空格,效果:{ foo: bar }。
  jsxBracketSameLine: true, // jsx > 是否另起一行
  arrowParens: 'always', // (x) => {} 是否要有小括号
}

配置eslint

bash
npm init @eslint/config
typescript
import pluginJs from '@eslint/js'
import tseslint from 'typescript-eslint'
import pluginVue from 'eslint-plugin-vue'

export default [
  pluginJs.configs.recommended,
  ...tseslint.configs.recommended,
  ...pluginVue.configs['flat/recommended']
]
// eslint.config.mjs  => esModule
// eslint.cjs         => common.js
// eslint.config.js文件根据package中"type": "module", 自动转换导出格式

eslint-plugin-vue

typescript
pluginVue.configs["flat/recommended"]   推荐这个!

 
flat/essential    				 => 简单必要版  (小杯)
flat/strongly-recommended  => 加强版      (中杯)
flat/recommended  				 =>  完整版包含了上面两种所有规则,最严格 (大杯)
  1. **flat/strongly-recommended: **启用识别和防止错误的规则,并且会通过一些对 Vue.js 的最佳实践来改善你的代码。这些最佳实践主要是为了增加代码的可读性和可维护性。
  2. flat/recommended: 包括了所有的 flat/essential 和 flat/strongly-recommended 的规则,还包括一些额外的规则,主要是为了防止一些可能的错误。这个配置是官方推荐的配置。

eslint.config.js

  • 使用 ESLint v9.0.0 时,请确保至少升级到 Node.js v18.18.0
typescript
import pluginJs from '@eslint/js'
import tseslint from 'typescript-eslint'
import pluginVue from 'eslint-plugin-vue'

export default [
  pluginJs.configs.recommended,
  ...tseslint.configs.recommended,
  // pluginVue 的 flat/recommended 不支持ts,需要手动指定
  ...pluginVue.configs['flat/recommended'],
  // 为使用ts的vue指定parser
  {
    files: ['**/*.vue'],
    languageOptions: {
      parser: vue_parser,
      parserOptions: {
        sourceType: 'module',
        parser: {
          ts: tseslint.parser
        }
      }
    }
  },
  {
    rules: {
      // 自定义规则
      // "no-unused-vars": "warn", 
    }
  }
]
  • "off" or 0 - turn the rule off
  • "warn" or 1 - turn the rule on as a warning (doesn’t affect exit code)
  • "error" or 2 - turn the rule on as an error (exit code will be 1)

v8.5.7 node16

  • 注意低版本eslint配置
typescript
npm init @eslint/config

eslint保存自动修复

VSCode 在 settings.json 设置文件中,增加以下代码:

typescript
// 当保存的时候,eslint自动帮我们修复错误
"editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
 }
typescript
// 保存代码,自动格式化 , 看心情要不要自动格式化!
"editor.formatOnSave": true

解决prettier和eslint冲突

Prettier 和 ESLint 可能存在冲突,因为它们都可以进行代码格式化,并可能对代码格式有各自不同的规则 理想情况下,应该让 Prettier 负责代码格式化,让 ESLint 负责检查代码质量,使得两者各司其职。

安装两个插件

解决两者冲突问题,需要用到 eslint-plugin-prettiereslint-config-prettier

  • eslint-plugin-prettier 将 Prettier 的规则设置到 ESLint 的规则中,作为Eslint规则使用。
  • eslint-config-prettier 禁用所有与 Prettier 冲突的 ESLint 规则。
bash
pnpm i --save-dev eslint-config-prettier eslint-plugin-prettier

在eslint配置文件添加 prettier 插件

.eslintrc.json(或者你用来配置 ESLint 的任何文件)中添加 Prettier 插件和配置

json
{
    "extends": ["prettier"],
    "plugins": ["prettier"],
    "rules": {
        "prettier/prettier": "error"
    },
}
  • .eslintrc.js
typescript
module.exports = {
  ...
  extends: [
    'plugin:vue/essential',
    'airbnb-base',
    'plugin:prettier/recommended' 
    // 添加 prettier 插件
  ],
  ...
}
  • eslint.config.js
javascript
import pluginJs from '@eslint/js'
import tseslint from 'typescript-eslint'
import pluginVue from 'eslint-plugin-vue'
import vueParser from 'vue-eslint-parser'

export default [
  pluginJs.configs.recommended,
  ...tseslint.configs.recommended,
  // pluginVue 的 flat/recommended 不支持ts,需要手动指定
  ...pluginVue.configs['flat/recommended'],
  {
    extends: [
      // 你已有的其他 extends 配置
      'prettier'
    ],
    plugins: [
      // 你已有的其他 plugins 配置
      'prettier'
    ],
    rules: {
      // 你已有的其他 rules 配置
      'prettier/prettier': 'error'
    }
  }
]

集成 husky 和 lint-staged

在代码提交前,进行代码规范检测,让没通过 ESLint 检测和修复的代码禁止提交,从而保证仓库代码都是符合规范的。

为了解决这个问题,我们需要用到 Git Hook,在本地执行 git commit 的时候,就对所提交的代码进行 ESLint 检测和修复(即执行 eslint --fix),如果这些代码没通过 ESLint 规则校验,则禁止提交。 实现这一功能,我们借助 husky + lint-staged

  • husky —— Git Hook 工具,可以设置在 git 各个阶段(pre-commitcommit-msgpre-push 等)触发我们的命令。
  • lint-staged —— 在 git 暂存的文件上运行 linters。

配置 husky

  • 安装
bash
pnpm add --save-dev husky
  • 初始化(推荐)

init 命令简化了项目中husky的设置。它在 .husky/ 中创建pre-commit钩子脚步并更新 package.json 中的 prepare 脚本

bash
# pnpm
pnpm exec husky init
# npm 
npx husky init
  • pre-commit hook 文件的作用是:

当我们执行 git commit -m "xxx" 时,会对 src 目录下所有的 .vue、.js、.ts 文件执行 eslint --fix 命令,如果 ESLint 通过,成功 commit,否则终止 commit。

配置 lint-staged

但是又存在一个问题:有时候我们明明只改动了一两个文件,却要对所有的文件执行 eslint --fix 我们要做到只用 ESLint 修复自己此次写的代码,而不去影响其他的代码。所以我们还需借助一个神奇的工具 **lint-staged**

lint-staged 这个工具一般结合 husky 来使用,它可以让 husky 的 hook 触发的命令只作用于 git add那些文件(即 git 暂存区的文件),而不会影响到其他文件

  • 安装
bash
pnpm i --save-dev lint-staged
  • package.json中配置
arkts
"scripts": {
  "dev": "vite",
    "build": "vue-tsc && vite build",
    "preview": "vite preview",
    "prepare": "husky"
},
// 配置lint-staged
"lint-staged": {
  "*.{vue,js,ts}": "eslint --fix"
},
// 表示:只对 git 暂存区的 .vue、.js、.ts 文件执行 eslint --fix
"dependencies": {
  "vue": "^3.4.21"
},

commit提交规范


Error解决

typescript
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
// Error 找不到path类型声明

export default defineConfig({
  plugins: [vue()]
})
bash
# 安装引入node的类型声明
pnpm i @types/node -D

参考