Vue CLI 创建的 Vue2 项目从 JavaScript 转换为 TypeScript

本文环境

@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

  1. extends 节点增加 '@vue/typescript/recommended'
  2. 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 即可

至此完成升级

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值