项目搭建
创建初始项目
Node.js 版本 14.18+,16+
npm create vite@latest my-vue-app --template vue-ts
添加eslint
-
eslint 初始化
npm init @eslint/config
eslint初始化脚本,按自己的要求选择相应的eslint 配置,以下是我选择的配置项
✔ How would you like to use ESLint? · style
✔ What type of modules does your project use? · esm
✔ Which framework does your project use? · vue
✔ Does your project use TypeScript? · No / Yes
✔ Where does your code run? · browser
✔ How would you like to define a style for your project? · guide
✔ Which style guide do you want to follow? · standard-with-typescript
✔ What format do you want your config file to be in? · JavaScript经过检查本地的依赖然后列出配置项所需的依赖:
会提示我们是否立即下载依赖,下载完成后会在根目录下自动生成eslint配置文件, 以下是我生成的配置文件
.eslintrc.cjs
,生成配置文件后,我们可以通过overrides指定eslint校验的范围,也可以自定义校验规则。此时我们的项目里可能会报错, 我们需要改一下tsconfig的配置,(项目搭建问题记录Q3)。
module.exports = {env: {browser: true,es2021: true,},extends: ["plugin:vue/vue3-essential", "standard-with-typescript"],overrides: [{files: "src/*.{js,ts,vue}", // 指定检查的目标文件,不需要额外添加.eslintignore},],parserOptions: {ecmaVersion: "latest",sourceType: "module",project: "tsconfig.json",},plugins: ["vue"],rules: {"@typescript-eslint/triple-slash-reference": "off", // 允许三斜杠引用其他模块的类型}, };
-
在package.json 配置eslint修复脚本
"scripts": {"dev": "vite","build": "vue-tsc && vite build","preview": "vite preview","eslint": "eslint --ext src/*.{js,ts,vue} --fix",},
添加prettier
-
下载依赖
npm install prettier eslint-config-prettier --save-dev
eslint-config-prettier: 防止eslint 规则和prettier 格式化规则冲突,冲突的规则将使用prettier的规则
-
在根目录下创建配置文件.prettierrc.json和格式化忽略文件.prettierignore
{"printWidth": 120,"tabWidth": 2,"semi": true,"trailingComma": "none","arrowParens": "avoid","endOfLine": "auto"}
-
在package.json 配置格式化脚本 format
"scripts": {"dev": "vite","build": "vue-tsc && vite build","preview": "vite preview","eslint": "eslint --ext src/*.{js,ts,vue} --fix","format": "prettier --write ."},
添加husky && lint-staged
-
下载依赖
npm install --save-dev husky lint-staged npx husky install npm pkg set scripts.prepare="husky install" npx husky add .husky/pre-commit "npx lint-staged"
-
在package.json 添加配置
"lint-staged": {"*.{js,ts,vue}": ["npm run eslint","npm run format"]}
项目搭建问题记录
-
Module ‘“xx.vue“‘ has no default export.Vetur(1192)
A: Vue2 使用
Vetur
用于 Vue 语法的支持的高亮,Vue3 官方推荐使用Volar
拓展,我们将Vetur
拓展卸载就可以了。 -
eslint 报错
Error while loading rule '@typescript-eslint/dot-notation': You have used a rule which requires parserServices to be generated. You must therefore provide a value for the "parserOptions.project" property for @typescript-eslint/parser.
A:
eslintrc.cjs
配置 parserOptions.projectparserOptions: {ecmaVersion: "latest",sourceType: "module",project: "tsconfig.json", // 添加解析配置 }
-
tsconfig.json
下moduleResolution: "bundler"
会提示波浪线,报错提示在没有 "node" 模块解析策略的情况下,无法指定选项 "-resolveJsonModule"。ts
A: 将moduleResolution: “node”, 并移除allowImportingTsExtensions: true