vite 构建 vue3
基础配置
本地配置:域名、端口、自启动浏览器
// vite.config.js 文件
export default defineConfig({
...,
server: {
host: "localhost",
port: 8080,
open: true,
},
});
代码规范
检查(Eslint) & 格式(Prettier)
Eslint:代码检查工具,偏向于把控项目的代码质量。
Prettier: 代码格式化工具,偏向于把控项目的编码风格。
1. 安装相关插件
/* 1. Vscode 安装扩展插件 - Eslint */
/* 2. 安装依赖包 */
// eslint:【核心库】检测代码中的语法错误和潜在的 bug
// eslint-plugin-vue:【插件库】Vue 的 ESLint 语法检查插件,检查 vue 文件错误并有效追踪提示
// eslint-plugin-import:【插件库】airbnb 规范的依赖库
// eslint-config-airbnb-base:【规范库】 airbnb 公司规范
// prettier:【核心库】检测代码中格式问题
// eslint-config-prettier:【规范库】 解决 eslint 与 prettier 的冲突,以 prettier 规范为准
// eslint-plugin-prettier:【插件库】eslint 检查代码时,按照 prettier 的规则检查代码规范性并进行修复
npm i -D eslint eslint-plugin-vue eslint-plugin-import eslint-config-airbnb-base prettier eslint-config-prettier eslint-plugin-prettier
2. 生成并配置 .eslintrc.cjs 文件
2.1 生成 .eslintrc.cjs 文件
生成指令:
/* 方式一: 命令行执行下方代码 */
npm init @eslint/config
/* 方式二:本质上也是调用方式一 */
// 1. 配置 package.json 文件中的 script 脚本
"scripts": {
...,
"lint:create": "eslint --init"
},
// 2. 命令行执行下方代码
npm run lint:create
生成过程:
2.2 安装依赖包
// eslint-import-resolver-alias:Node.js 模块导入解析插件,用于 eslint-plugin-import,模块别名/映射和自定义文件扩展名(如:import 时可以使用 @ 别名)
// vue-eslint-parser:这个解析器允许我们检测.vue文件的<template>。如果在模板中使用复杂的指令和表达式,我们很容易在<template>上犯错误。这个解析器和eslint-plugin-vue的规则可以捕捉到一些错误。
npm i -D eslint-import-resolver-alias vue-eslint-parser
typescript 版本需要额外安装以下依赖
// @typescript-eslint/parser:EsLint的解析器,用于解析、检查和规范 ts 代码
// @typescript-eslint/eslint-plugin:ESLint插件,包含各类定义好的检测 ts 代码规范
// @types/eslint:包含eslint的类型定义
// @types/node:包含Node.js的类型定义
npm i -D typescript @typescript-eslint/parser @typescript-eslint/eslint-plugin @types/eslint @types/node
2.3 配置 .eslintrc.cjs 文件
module.exports = {
// 环境
env: {
browser: true, // 浏览器
es2021: true, // 最新 es 语法
node: true, // node 环境
},
// 继承(eslint-config- 前缀可忽略不写):数组中每个配置都会继承前一项
// extends: ["eslint:recommended", "plugin:vue/vue3-essential"],
extends: ["plugin:vue/vue3-strongly-recommended", "airbnb-base", "prettier"],
overrides: [],
// 解析器
parser: "vue-eslint-parser",
// 解析器配置
parserOptions: {
ecmaVersion: "latest",
sourceType: "module",
},
// 全局变量:配置后源文件使用全局变量不会警告或报错
globals: {
defineProps: "readonly",
defineEmits: "readonly",
defineExpose: "readonly",
withDefaults: "readonly",
},
// 插件(eslint-config- 前缀可忽略不写)
plugins: ["vue"],
// 设置
settings: {
// 设置别名
"import/resolver": {
alias: {
map: [
['~', './'],
['@', './src'],
],
extensions: ['.js', '.jsx', '.ts', '.tsx', '.vue', 'svg'],
},
},
},
// 自定义规则:覆盖上面 extends 继承的第三方库的规则
rules: {
"import/no-extraneous-dependencies": 0,
"no-param-reassign": 0,
"vue/multi-word-component-names": 0,
"vue/attribute-hyphenation": 0,
"vue/v-on-event-hyphenation": 0,
},
};
注意:使用别名时需要在 vite.config.js 文件中单独进行配置
import path from 'path'
// https://vitejs.dev/config/
export default defineConfig({
...,
resolve: {
alias: {
// 设置路径
'~': path.resolve(__dirname, './'),
// 设置别名
'@': path.resolve(__dirname, './src'),
},
},
})
typescript 需要添加以下配置
module.exports = {
// 解析器配置
parserOptions: {
...,
parser: "@typescript-eslint/parser",
ecmaFeatures: {
tsx: true,
jsx: true,
},
},
plugins: [... , "@typescript-eslint"],
};
2.4 禁止 ESLint 检查
禁用 js 中 ESLint 检查
// eslint-disable-next-line vue/no-async-in-computed-properties
const test = computed(async () => {
return count.value + 2;
});
注释中:
eslint-disable-next-line
指的是禁止 ESLint 检查下一行代码。vue/no-async-in-computed-properties
是 Vue ESLint 插件提供的规则名,即禁止这项规则的检查,更多的规则可以参考这个网站 https://eslint.vuejs.org/rules/。
禁用 template 中 ESLint 检查
<!-- eslint-disable-next-line ... -->
3. 配置脚本命令并实现自动检测 eslint 规范
3.1 package.json 文件增加一个 lint 命令
// package.json文件
"scripts": {
...,
"lint": "eslint . --ext .vue,.js,.ts,.jsx,.tsx --fix" // lint当前项目中的文件并且开启自动修复
},
3.2 vite 运行时自动检测 eslint 规范
// vite-plugin-eslint:vite运行时自动检测eslint规范
npm i -D vite-plugin-eslint
// vite.config.js 文件
import eslintPlugin from 'vite-plugin-eslint';
export default defineConfig({
plugins: [..., eslintPlugin()],
});
4. 添加 prettier 配置文件并配置脚本命令
4.1 添加 prettier 格式化文件
// .prettierrc.cjs 文件
module.exports = {
//一行最多 100 字符
printWidth: 80,
//使用 2 个空格縮迸
tabWidth: 2,
//不使用縮迸符,而使用空格
useTabs: false,
//行尾需要有分号
semi: true,
//使用単引号
singleQuote: true,
//对象的 key 仅在必要时用引号
quoteProps: 'as-needed',
//jsx 不使用単引号,而使用双引号
jsxSingleQuote: false,
//尾随逗号
trailingComma: 'es5',
//大括号内的首尾需要空格
bracketSpacing: true,
// 箭头函数,只有一个参数的时候,也需要括号
arrowParens: 'always',
//每介文件格式化的范国是文件的全部内容
rangeStart: 0,
rangeEnd: Infinity,
//不需要写文件开头的 @prettier
requirePragma: false,
//不需要自动在文件开头插入 @prettier
insertPragma: false,
//使用默认的折行标准
proseWrap: 'always',
//根据显示样式决定 html 要不要折行
htmlWhitespaceSensitivity: 'css',
// 换行符使用 lf
endOfLine: 'lf',
};
4.2 package.json 文件增加一个 prettier-format 命令
// package.json文件
"scripts": {
...,
"prettier-format": "prettier --config .prettierrc.cjs \"src/**/*.{vue,js,ts}\" --write" // 利用prettier手动格式化一些样式问题
},
5. 添加忽略文件
// .eslintignore 文件
*.sh
node_modules
*.md
*.woff
*.ttf
.vscode
.idea
dist
/public
/docs
.husky
/bin
.eslintrc.js
prettier.config.js
sre mock/*
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
.DS_Store
dist-ssr
*.local
/cypress/videos/
/cypress/screenshots/
# Editor directories and files
.vscode
!.vscode/extensions.json
.idea
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
components.d.ts
// .prettierignore 文件
dist/*
.local
.output.js
/node_modules/**
src/.DS_Store
**/*.svg
***.sh
/public/*
components.d.ts
6. typescript 版本配置 tsconfig.json 文件
// tsconfig.json 文件
{
"compilerOptions": {
//指定es的目标版本
"target": "esnext",
"useDefineForClassFields": true,
// "isolatedModules": true,
"module": "esnext",
//決定如处理模块
"moduleResolution": "node",
"strict": true,
"strictNullChecks": false,
"jsx": "preserve",
"sourceMap": true,
"resolveJsonModule": true,
"esModuleInterop": true,
//编译过程中需要引入的库文件的列表
"lib": ["esnext","dom", "DoM.Iterable"],
//默认所有可见的"@types"包会在编泽过程中被包含进来
"types" : ["vite/client"],
//解析非相对模块名的基准目录
"baseUrl" :".",
//模块名到基于 baseUrl 的路径映射的列表
"paths": {
"@/*": ["src/*"],
"*.ts": ["*"]
},
},
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
}
代码提交检测
Git 钩子(husky) & Git commit 时对提交代码校验(lint-staged)
1. 安装依赖
// husky:git hook 工具,执行 git 操作前自动触发函数
// lint-staged:对暂存的 git 文件运行 lint 程序,进行代码校验
npm i -D husky lint-staged
2. package.json 文件配置脚本命令
// package.json 文件
"scripts": {
...,
"prepare": "husky install"
},
3. 执行脚本命令安装 husky
// 执行脚本命令前需要确定 .git 文件夹的存在(不存在可先执行 git init 创建)
npm run prepare
4. 添加 git hook 并配置脚本命令
// 4.1 pre—commit:该钩子使 lint—staged 对 git 暂存区代码进行格式化处理
npx husky add .husky/pre-commit "npx lint-staged"
// 4.2 配置 package.json 文件脚本命令
{
...,
"lint-staged": {
"*.{js,jsx,vue,ts,tsx}": [
"npm run lint",
"npm run prettier-format"
]
}
}
// Mac 系统中若提交时出现【提示:因为没有将钩子 '.husky/pre-commit' 设置为可执行,钩子被忽略。】执行以下命令更改文件为可执行即可。
chmod +x .husky/pre-commit
Git commit 时对提交描述检验(commitlint)
1. 安装依赖
npm i -D @commitlint/config-conventional @commitlint/cli
2. 添加 hook
npx husky add .husky/commit-msg "npx --no -- commitlint --edit ${1}"
3. 添加文件 commitlint.config.cjs
// commitlint.config.cjs 文件
module.exports = {
extends: ['@commitlint/config-conventional'],
rules: {
'type-enum': [
2,
'always',
[
'build', // 编译相关的修改,例如发布版本、对项目构建或者依赖的改动
'feat', // 新功能 (feature)
'fix', // 修复bug
'upd', // 更新某功能
'refactor', // 重构
'docs', // 文档 (documentation)
'chore', // 构建过程或辅助工具的变动,比如增加依赖库等
'style', // 格式(不影响代码运行的变动)
'revert', // 撤销commit,回滚到上一个版本
'perf', // 性能优化
'test', // 测试(单元、集成测试)]
],
],
'type-case': [0],
'type-empty': [0],
'scope-empty': [0],
'scope-case': [0],
'subject-full-stop': [0, 'never'],
'subject-case': [0, 'never'],
'header-max-length': [0, 'always', 72],
},
}
https://github.com/angular/angular/blob/main/CONTRIBUTING.md
常用的git hooks
pre-commit 由git commit 调用,在commit 之前执行
commit-msg:由git commit 或 gitmerge 调用
pre-merge-commit 由gitmerge 调用,在merge 之前执行
pre-push:被git push 调用,在git push 前执行,防止进行推送
样式代码检测
1. 安装 Vscode 插件
// 1.1 Vscode 扩展中搜索安装 - StyleLint
// 1.2 若要实现保存后自动格式化,在 settings.json 文件进行如下配置
{
...,
"editor.codeActionsOnSave": {
...,
"source.fixAll.stylelint": true
},
"stylelint.validate": ["css", "scss", "less", "vue"],
}
2. 安装相关依赖并进行配置
/* 2.1 安装依赖 */
// sass
// stylelint: 校验库
// stylelint-config-standard:规范库
// stylelint-config-standard-scss
// stylelint-config-prettier
// stylelint-config-recess-order (可选)
// stylelint-config-recommended-vue (可选)
// postcss
// postcss-html
npm i -D sass stylelint stylelint-config-standard stylelint-config-standard-scss stylelint-config-prettier stylelint-config-recess-order stylelint-config-recommended-vue postcss postcss-html
/* 2.2 添加配置文件 .stylelintrc.cjs 使用相关规范 */
module.exports = {
extends: [
'stylelint-config-standard', // (可选)
'stylelint-config-standard-scss',
'stylelint-config-recommended-vue',
'stylelint-config-recess-order', // (可选)
'stylelint-config-prettier', // (可选)
],
}
/* 2.3 package.json 文件配置脚本命令,使用此命令对样式文件进行规范校验 */
"scripts": {
...,
// "lint:css": "stylelint **/*.{html,css,vue,sass,scss,less} --fix"
"lint:css": "stylelint **/*.{css,vue,sass,scss} --fix"
},
3. 安装 vite eslint 插件实现在 git hook 自动执行样式规范校验
// 3.1 安装插件
npm i -D vite-plugin-stylelint
// 3.2 vite.config.js 文件中使用该插件
import stylelintPlugin from 'vite-plugin-stylelint'
export default defineConfig({
plugins: [..., stylelintPlugin({ fix: true })],
})
// 3.3 package.json 文件配置脚本命令,实现 git hook 触发时自动执行样式规范校验
{
...,
"lint-staged": {
...,
"*.{css,sass,scss,less,vue}": [
"npm run lint:css"
]
}
}
4. 添加 stylelint 过滤文件
// .stylelintignore
# .stylelintignore
# 旧的不需打包的样式库
*.min.css
# 其他类型文件
*.js
*.jpg
*.png
*.eot
*.ttf
*.woff
*.json
# 测试和打包目录
/dist/*
/public/*
public/*
/node_modules/
/test/
环境变量和模式
1. 添加环境变量文件
import.mate.env
- 开发环境
.env.development
文件
# 开发环境配置
ENV = 'development'
# 开发环境
VITE_APP_BASE_URL = ''
- 生产环境
.env.production
文件
# 生产环境配置
ENV = 'production'
# 生产环境
VITE_APP_BASE_API = ''
- 测试环境
.env.testing
文件
# 测试环境配置
ENV = 'testing'
# 测试环境
VITE_APP_BASE_API = ''
2. package.json 文件配置项目打包脚本命
// 非 ts 版
{
...,
"scripts": {
...,
"build:dev": "vite build --mode development",
"build:test": "vite build --mode testing",
},
}
// ts 版本
{
...,
"scripts": {
...,
"build:dev": "vue-tsc --noEmit && vite build --mode development",
"build:test": "vue-tsc --noEmit && vite build --mode testing",
},
}
项目 setting.json 文件
.vscode/setting.json
:.vscode
中添加 setting.json
文件
{
"editor.tabSize": 2,
"editor.codeActionsOnSave": {
"source.fixAll": true,
"source.fixAll.eslint": true,
"source.fixAll.stylelint": true
},
"[html]": {
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[css]": {
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[scss]": {
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[less]": {
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[javascript]": {
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[vue]": {
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[json]": {
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
// stylelint
"stylelint.validate": ["css", "scss", "less", "vue"],
}
Vscode 调试
.vscode/launch.json
:.vscode
中添加 launch.json
文件
// https://code.visualstudio.com/docs/editor/debugging#_launch-configurations
{
"version": "0.2.0",
"configurations": [
{
"type": "chrome",
"request": "launch",
"name": "Launch Chrome",
"url": "http://127.0.0.1:8080",
"webRoot": "${workspaceFolder}/src",
"sourceMaps": true
}
]
}
vue 路由
1. 安装依赖
npm install vue-router@4