TypeScript从入门到Vue项目迁移

1. 前言

ES6的普及,大大简化了JavaScript的表达方式

大型项目中,js没有类型检查、表达方式灵活,多人协作代码调试和维护成本高

2. 定义

TypeScriptJavaScript 的一个超集,而且本质上向这个语言添加了可选的静态类型和基于类的面向对象编程,可以理解成是 js 的强类型版本

这里的Type:类型(指的就是静态类型检查)

3. 走马观花学一下

npm安装:

npm install -g typescript

新建ts.ts文件如下:

function hello(msg: string): void {
  console.log(`hello, ${msg}`);
}

hello('kwin');

运行命令,会编译出一个ts.js文件,这样js文件可以在浏览器或者node环境中运行

tsc ts.ts

由于最终在浏览器中运行的仍然是 JavaScript,所以 TypeScript 并不依赖于浏览器的支持,也并不会带来兼容性问题

接下来看看文档,

静态类型分为:基础类型、接口、类、函数、泛型、枚举等

接口(Interface):为类型命名和为你的代码或第三方代码定义契约

类(Class):以往在js中我们使用函数和基于原型的继承来创建可重用的组件,ts中是基于类的继承 对象是由类构建出来的

工程配置文件:tsconfig.json 看到这个文件说明是ts项目的根目录

使用外部依赖的时候需要书写声明文件 >> .d.ts

参考:
TypeScript中文文档
TypeScript手册

4. js => ts 迁移

ts 中可以使用 纯js

项目重构初期可以考虑ts js 并存,逐步替换,下面着重看下Vue项目向ts的迁移

4.1 安装依赖

vue的官方插件

npm i vue-class-component vue-property-decorator --save

ts-loader typescript tslint等

npm i ts-loader typescript tslint tslint-loader tslint-config-standard --save-dev

这些库大体的作用:

  • vue-class-component:强化 Vue 组件,使用 TypeScript/装饰器 增强 Vue 组件

  • vue-property-decorator:在 vue-class-component 上增强更多的结合 Vue 特性的装饰器

  • ts-loader:TypeScript 为 Webpack 提供了 ts-loader,其实就是为了让webpack识别 .ts .tsx文件

  • tslint-loader跟tslint:我想你也会在.ts .tsx文件 约束代码格式(作用等同于eslint)

  • tslint-config-standard:tslint 配置 standard风格的约束

4.2 配置webpack 设置ts解析

entry: {
  app: './src/main.ts'
},
resolve: {
  extensions: ['.js', '.vue', '.json', '.ts'],
  ...
},
module: {
  rules: [
    {
      test: /.vue$/,
      loader: 'vue-loader',
      options: vueLoaderConfig
    },
    {
        test: /.js$/,
        loader: 'babel-loader',
        include: [
            resolve('src'),
            resolve('test'),
            resolve('node_modules/webpack-dev-server/client'),
        ],
    },
    {
        test: /.ts$/,
        exclude: /node_modules/,
        enforce: 'pre',
        loader: 'tslint-loader',
    },
    {
        test: /.tsx?$/,
        loader: 'ts-loader',
        exclude: /node_modules/,
        options: {
            appendTsSuffixTo: [/.vue$/]
        }
    },
    ...
  ]
},

4.3 添加 tsconfig.json

在项目根目录下创建tsconfig.json,参考配置如下:

{
  // 编译选项
  "compilerOptions": {
    // 输出目录
    "outDir": "./output",
    // 是否包含可以用于 debug 的 sourceMap
    "sourceMap": true,
    // 以严格模式解析
    "strict": true,
    // 采用的模块系统
    "module": "esnext",
    // 如何处理模块
    "moduleResolution": "node",
    // 编译输出目标 ES 版本
    "target": "es5",
    // 允许从没有设置默认导出的模块中默认导入
    "allowSyntheticDefaultImports": true,
    // 将每个文件作为单独的模块
    "isolatedModules": false,
    // 启用装饰器
    "experimentalDecorators": true,
    // 启用设计类型元数据(用于反射)
    "emitDecoratorMetadata": true,
    // 在表达式和声明上有隐含的any类型时报错
    "noImplicitAny": false,
    // 不是函数的所有返回路径都有返回值时报错。
    "noImplicitReturns": true,
    // 从 tslib 导入外部帮助库: 比如__extends,__rest等
    "importHelpers": true,
    // 编译过程中打印文件名
    "listFiles": true,
    // 移除注释
    "removeComments": true,
    "suppressImplicitAnyIndexErrors": true,
    // 允许编译javascript文件
    "allowJs": true,
    // 解析非相对模块名的基准目录
    "baseUrl": "./",
    // 指定特殊模块的路径
    "paths": {
      "jquery": [
        "node_modules/jquery/dist/jquery"
      ]
    },
    // 编译过程中需要引入的库文件的列表
    "lib": [
      "dom",
      "es2015",
      "es2015.promise"
    ]
  }
}

4.4 添加 tslint.json

在项目根目录下创建tslint.json,即引入ts的规范

{
  "extends": "tslint-config-standard",
  "globals": {
    "require": true
  }
}

4.5 让 ts 识别 .vue

在src目录下创建 vue-shim.d.ts

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

4.6 修改 .vue文件

<template><style> 都不用修改,

<script lang="ts">
import Vue from 'vue'
import Component from 'vue-class-component'

// @Component 修饰符注明了这是一个Vue组件
@Component({
  // 组件可以在这里定义
  components: {
    // NavHeader
  }
})
export default class HelloWorld extends Vue {
  // 初始数据可以直接声明
  msg: string = 'Welcome to Your Vue.js App'

  // 组件的方法也可以直接声明
  greet() {
    alert('greeting: ' + this.msg)
  }

  mounted() {
    this.greet()
  }

  // 计算属性
  get computedMsg() {
    return 'computed ' + this.msg
  }
}
</script>

4.7 npm run dev 运行即可

参考:vue + typescript

5. Vue3.0 TypeScript

Vue3.0将会用 ts 重构

3.x版本的脚手架已经发布:@vue/cli

下个版本,TypeScript的时代,一起期待吧!

原文地址:https://www.cnblogs.com/kaidarwang/p/11309375.html