本文环境
@vue/cli 5.0.8
tsconfig.json
新增 tsconfig.json 到项目根目录,其内容为:
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"strict": true,
"jsx": "preserve",
"moduleResolution": "node",
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"useDefineForClassFields": true,
"sourceMap": true,
"baseUrl": ".",
"types": [
"webpack-env"
],
"paths": {
"@/*": [
"src/*"
]
},
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"tests/**/*.ts",
"tests/**/*.tsx"
],
"exclude": [
"node_modules"
]
}
同时,删除根目录下的 jsconfig.json
.eslintrc.js
- extends 节点增加 '@vue/typescript/recommended'
- parserOptions 节点的 parser: '@babel/eslint-parser' 更改为 ecmaVersion: 2020
完整修改后:
module.exports = {
root: true,
env: {
node: true
},
'extends': [
'plugin:vue/essential',
'eslint:recommended',
'@vue/typescript/recommended'
],
parserOptions: {
ecmaVersion: 2020
},
rules: {
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off'
}
}
src 文件夹
- src 文件夹下,main.js 改名为 main.ts
- src/router 文件夹下,index.js 改名为 index.ts
- src 文件夹下,新增 shims-tsx.d.ts 文件
import Vue, { VNode } from 'vue'
declare global {
namespace JSX {
interface Element extends VNode {}
interface ElementClass extends Vue {}
interface IntrinsicElements {
[elem: string]: any
}
}
}
- src 文件夹下,新增 shims-vue.d.ts 文件
declare module '*.vue' {
import Vue from 'vue'
export default Vue
}
package.json
删除依赖:
- "@babel/core": "^7.12.16"
- "@babel/eslint-parser": "^7.12.16"
新增依赖:
- "@typescript-eslint/eslint-plugin": "^5.4.0"
- "@typescript-eslint/parser": "^5.4.0"
- "@vue/cli-plugin-typescript": "~5.0.0"
- "@vue/eslint-config-typescript": "^9.1.0"
- "typescript": "~4.5.5"
删除依赖指令:
npm rm @babel/core @babel/eslint-parser
新增依赖指令:
npm install --save-dev @typescript-eslint/eslint-plugin@^5.4.0
npm install --save-dev @typescript-eslint/parser@^5.4.0
npm install --save-dev @vue/cli-plugin-typescript@~5.0.0
npm install --save-dev @vue/eslint-config-typescript@^9.1.0
npm install --save-dev typescript@~4.5.5
但安装新依赖时,可能因为之前安装的各种依赖冲突而报错,所以建议以下另一种方法:
直接编辑 package.json,删除和新增上述的依赖后,把项目根目录下的 node_modules 文件夹和 package-lock.json 删除掉,再运行 npm i 重新安装所有依赖
如果 VsCode 内有文件显示报错(例如 tsconfig.json),重启一次 VsCode 即可
至此完成升级