Skip to main content

Vue2.X中将js迁移为TypeScript步骤及注意点

· 预计阅读时间:2 分钟
note

为什么要迁移呢?看到这里肯定不用说了,肯定是由自己的需求的不然应该也不会看到这里,我就是这样,哈哈哈。那么如何将已有的Vue项目(已经有一个通过 vue-cli3 脚手架构建的 vue 项目)迁移至Typescript呢?

1、安装依赖#

假设已经有一个通过 vue-cli3 脚手架构建的 vue 项目,那么我们来安装相关的依赖吧。

  • 1.1、typescript
  • 1.2、@vue/cli-plugin-typescript
  • 1.3、Vue-class-component
  • 1.4、Vue-property-decorator
  • 1.5、vuex-class
npm i typescript  ts-loader vue-class-component vue-property-decorator vuex-class 

2、项目中添加Typescript配置#

根目录下新建 tsconfig.json,下面为一份配置实例(点击查看所有配置项:https://www.tslang.cn/docs/handbook/tsconfig-json.html)。

{  "compilerOptions": {    "target": "esnext",    "module": "esnext",    "strict": true,    "jsx": "preserve",    "importHelpers": true,    "moduleResolution": "node",    "experimentalDecorators": true,    "skipLibCheck": true,    "esModuleInterop": true,    "allowSyntheticDefaultImports": 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"  ]}

3、项目中添加shims-vue.d.ts文件#

项目src目录下新建shims-vue.d.ts文件

declare module "*.vue" {  import Vue from "vue";  export default Vue;}

4、修改入口文件后缀为.ts#

没啥区别 main.js=>main.ts

5、修改router文件#

import Vue from 'vue'import VueRouter , { RouteConfig }  from 'vue-router'
Vue.use(VueRouter)
const routes: Array<RouteConfig>  = [  {    path: '/',    redirect: "/goodsDetail"  },  {    path: '/goodsDetail',    name: 'GoodsDetail',    component: () => import('@/views/goodsDetails/index.vue')  },  {    path: '/result',    name: 'Result',    component: () => import('@/views/result/index.vue')  },  {    path: '/orderDetail',    name: 'OrderDetail',    component: () => import('@/views/orderDetail/index.vue')  },]
const router = new VueRouter({  routes})
router.beforeEach((to, from, next) => {  window.scrollTo(0, 0);  next();});export default router

6、修改store文件#

import Vue from 'vue'import Vuex from 'vuex'declare const window: Window & { WeixinJSBridge: any, WVJBCallbacks: any, __wxjs_environment: any };declare let WeixinJSBridge: anyVue.use(Vuex)
let store = new Vuex.Store({  modules: {  },  state: {    city: "",  },  mutations: {  },  actions: {
  }})

export default store;

7、注意事项#

  • 导入vue文件时必须带.vue的后缀
  • 如果有安装依赖找不到需要单独声明依赖在src文件夹下创建 依赖名.d.ts 然后在该文件中声明依赖
declare module 'js-sha1';
  • 如果明明存在的属性,ts无法识别时使用declare关键字重新声明一下比如WeixinJSBridge属性,重新声明如下declare let WeixinJSBridge: any
  • ts 扩展功能到Vue原型(this)可是ts访问不到,Vue2 在 type.d.ts 文件添加一下内容
export {} /// 这句不能删declare module 'vue/types/vue' {  class C1 {}  interface Vue {    a1: C1    a2: Function    a3: {      a2: 'a' | 'b'    }    a4: number | string | boolean | Function  }}