Vite + Vue3 + Typescript配置Vue3 ts项目基础开发框架
本基础开发框架包含:
eslint代码检查prettier格式化*.js、*.ts、*.jsx、*.tsx、*.vue、*.css、*.less、*.scss等文件- 文件保存时自动格式化代码
commitlint规范git提交信息- 支持
SFC、jsx、tsx混用 - 路由权限验证
- 暂时使用
ant-design-vue@2.2.8作为UI组件库
初始化项目
See: vite
# npm 6.x
npm create vite@latest projectName --template vue
# npm 7+
npm create vite@latest projectName -- --template vue
# yarn
yarn create vite projectName --template vue
# pnpm
pnpm create vite projectName -- --template vue
本项目使用yarn
目录结构为:
projectName
├── .vscode
│ └── extensions.json
├── public
│ └── favicon.ico
├── src
│ ├── assets
│ │ └── logo.png
│ ├── components
│ │ └── HelloWorld.vue
│ ├── App.vue
│ └── main.js
├── .gitignore
├── index.html
├── package.json
├── README.md
└── vite.config.js
配置eslint和prettier
配置eslint
See: eslint
npm install eslint -D
# or
yarn add eslint -D
然后创建配置文件:
npm init @eslint/config
# or
yarn create @eslint/config
依次选择:
- To check syntax and find problems
- Javascript modules (import/export)
- Vue.js
- Yes
- Browser
- Javascript
- Yes
生成配置文件.eslintrc.js:
module.exports = {
env: {
browser: true,
es2021: true,
},
extends: [
"eslint:recommended",
"plugin:vue/essential",
"plugin:@typescript-eslint/recommended",
],
parserOptions: {
ecmaVersion: "latest",
parser: "@typescript-eslint/parser",
sourceType: "module",
},
plugins: ["vue", "@typescript-eslint"],
rules: {},
};
vue3不需要单个根元素,将plugin:vue/essential改为plugin:vue/vue3-essential- 配置对
vue3的<script setup>块的支持,添加parser: 'vue-eslint-parser' - 让
vue3的<script setup>块不需要导入defineProps,在env选项中添加'vue/setup-compiler-macros': true - 配置对于
node、commonjs、amd模块的支持,在env选项中添加node: true、commonjs: true、amd: true - 配置对于
jsx的语法支持,在parserOptions选项中添加ecmaFeatures: { jsx: true } - 添加
.eslintignore文件,忽略dist文件夹和*.html文件
配置prettier
See: prettier
npm install --save-dev --save-exact prettier
# or
yarn add --dev --exact prettier
然后根目录创建.prettierrc.json,本项目的配置如下:
{
"arrowParens": "avoid",
"semi": false,
"singleQuote": true,
"trailingComma": "es5",
"quoteProps": "as-needed",
"tabWidth": 2
}
然后创建.prettierignore,添加需要忽略的文件或文件夹
处理eslint和prettier的冲突
安装eslint-config-prettier:
npm install -D eslint-config-prettier
# or
yarn add -D eslint-config-prettier
然后在.eslintrc.js的extends的最后添加prettier
配置git hooks和commitlint
配置git hooks
See: lint-staged
首先初始化git
git init
然后安装husky和lint-staged
npx mrm@2 lint-staged
需要将package.json中的"*.js": "eslint --cache --fix"改为"*.js": "eslint --fix",否则每次提交会生成一个缓存文件
然后在package.json中的lint-staged中添加对于*.ts、*.vue、*.tsx、*.less、*.scss等文件的格式化支持,现在提交代码的时候会自动格式化改动的文件
配置commitlint
防止git的commit信息混乱,使用commitlint规范提交信息,See: commitlint
npm install --save-dev @commitlint/config-conventional @commitlint/cli
# or
yarn add -D @commitlint/config-conventional @commitlint/cli
创建配置文件,本项目选择commitlint.config.js:
module.exports = {
extends: ['@commitlint/config-conventional'],
ignores: [commit => commit.includes('init')],
rules: {
'body-leading-blank': [2, 'always'],
'footer-leading-blank': [1, 'always'],
'header-max-length': [2, 'always', 108],
'subject-empty': [2, 'never'],
'type-empty': [2, 'never'],
'type-enum': [
2,
'always',
[
'feat',
'fix',
'perf',
'refactor',
'style',
'docs',
'test',
'build',
'ci',
'chore',
'revert',
'types',
'wip',
],
],
},
}
添加hooks
npx husky add .husky/commit-msg 'npx --no -- commitlint --edit $1'
# or
yarn husky add .husky/commit-msg 'yarn commitlint --edit $1'
配置vite
配置对于jsx语法的支持
安装@vitejs/plugin-vue-jsx
npm install -D @vitejs/plugin-vue-jsx
# or
yarn add -D @vitejs/plugin-vue-jsx
现在可以将vite.config.js改成vite.config.ts,并添加:
// vite.config.ts
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
export default defineConfig({
plugins: [vue(), vueJsx()],
})
为*.vue文件添加声明
src目录下添加env.d.ts声明文件,为*.vue文件添加声明,同时将vite的类型定义暴露给前端代码:
/// <reference types="vite/client" />
declare module '*.vue' {
import { DefineComponent } from 'vue'
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/ban-types
const component: DefineComponent<{}, {}, any>
export default component
}
然后在项目根目录添加tsconfig.json:
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"isolatedModules": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"esModuleInterop": true,
"strict": true,
"jsx": "preserve",
"allowJs": true,
"checkJs": true,
"sourceMap": true,
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
},
"lib": ["esnext", "dom"],
"types": ["vite/client"]
},
"include": ["src/**/*.ts", "src/**/*d.ts", "src/**/*.tsx", "src/**/*.vue"],
"exclude": ["node_modules"]
}
配置路径别名
// vite.config.ts
import path from 'path'
export default defineConfig({
resolve: {
alias: {
'@': path.resolve(__dirname, 'src')
},
},
})
配置环境变量
在项目根目录下创建.env.local、.env.test、.env.gray、.env.prod,分别表示本地开发环境、测试服、灰度或预生产、生产环境,文件内容为key=value的形式,其中key要以VITE_开头的形式,See: vite环境变量,可以使用#添加注释
然后,修改vite.config.ts:
// vite.config.ts
import path from 'path'
import { defineConfig, loadEnv, UserConfig } from 'vite'
export default defineConfig(({ command, mode }) => {
// 向`process.env`写入环境变量
process.env = { ...process.env, ...loadEnv(mode, process.cwd()) }
const IS_PROD = command === 'build'
const config: UserConfig = {
base: IS_PROD ? '/' : '/', // 根据实际情况配置
plugins: [
vue(),
vueJsx(),
],
resolve: {
alias: {
'@': path.resolve(__dirname, 'src'),
},
},
}
if (!IS_PROD) {
// 开发环境独有配置
} else {
// 生产环境独有配置
}
return config
})
配置vscode
-
安装
Volar扩展插件,将Vetur禁用(可以在本工作空间workspace中禁用),Volar是vscode对vue3支持的插件 -
在
.vscode文件夹下添加settings.json:{ "editor.formatOnSave": true, "eslint.validate": ["html", "vue", "javascript", "jsx", "ts", "tsx"], "eslint.format.enable": true, "editor.codeActionsOnSave": { "source.fixAll": true }, "[javascript]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[javascriptreact]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[json]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[scss]": { "editor.defaultFormatter": "esbenp.prettier-vscode" } }
到这里,项目基础配置差不多了,接下来可以根据需要配置vuex、vue-router、UI 组件等