美文网首页
vue2.5兼容ts

vue2.5兼容ts

作者: 小灰灰_a | 来源:发表于2022-01-16 11:01 被阅读0次

背景:

由于公司组织架构调整,本人很荣幸(日了狗)接手了一个公司二年前的vue2X项目,由于近期使用的技术框架是react+ts,Ts提供的静态类型检测及类型推断等功能可以减少代码的隐藏bug,大大减少bug,所以使用vue+js各种不习惯,虽然vue3对ts有了很好的支持,但是累计两年的代码量以及项目的依赖,直接升级的话,工程量会非常巨大,还好vue2.5X对ts有了一定的支持,只需要做一些简单的操作,就可以完成。

  • 首先按照ts的依赖
npm i -D typescript ts-loader 
  • 安装vue的解析依赖
npm i -D  vue-class-component @vue/eslint-config-prettier
  • 根目录添加 tsconfig.json
{
    "compilerOptions": {
      "target": "es5",
      "lib": [
        "dom",
        "dom.iterable",
        "esnext"
     ],
      "allowJs": true,
      "skipLibCheck": true,
      "esModuleInterop": true,
      "allowSyntheticDefaultImports": true,
      "strict": true,
      "forceConsistentCasingInFileNames": true,
      "noFallthroughCasesInSwitch": true,
      "module": "esnext",
      "moduleResolution": "node",
     "resolveJsonModule": true,
      "isolatedModules": true,
     "noEmit": false,
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true
    },
    "include": [
      "src",
    ]
 }
  • 在 src/ 添加 vue-shim.d.ts 解析 .vue文件
declare module "*.vue" {
    import Vue from 'vue'
    export default Vue
}
// 其他第三方js文件省去 *.d.ts
declare module "*"
  • .eslintrc.js 文件的修改
module.exports = {
    ...
     ecmaFeatures: {
        ...
        // 新增
       legacyDecorators: true
     },
   },
   extends: [
      ...
      // 新增
      "@vue/prettier"
   ],
  • webpack.base.conf.js 添加ts loader
resolve: {
   extensions: ['.js', '.vue', '.json', '.ts', '.tsx'], // 添加 .ts, .tsx
}
module: {
  rules: [
  ...
    {
        test: /\.tsx?$/,
        loader: 'ts-loader',
        exclude: /node_modules/,
        options: {
          appendTsSuffixTo: [/\.vue$/] // ts-loader
     }
  ]
}

相关文章

网友评论

      本文标题:vue2.5兼容ts

      本文链接:https://www.haomeiwen.com/subject/rckchrtx.html