Vue 2.6 中部分引入 TypeScript 的方法

在 Vue 与 Cesium 联合开发的过程中,我发现很多 Cesium 代码不宜直接写在 .vue 文件中。同时由于 Cesium 库较为复杂,不借助 TypeScript 的静态类型会导致代码难维护困难等问题。而我本身又不太愿意改变 Vue 现有的开发方式,因此决定通过在 Vue 中增加 TS 解析器的方式来解决以上问题。

步骤如下:

  1. 安装 typescript 和 ts-loader
npm install typescript ts-loader --save-dev
  1. 在根目录下新建 tsconfig.json 配置文件,配置文件可根据自己的需求设置,具体参考官网 [tsconfig.json] 配置指南
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "noImplicitAny": true,
    "removeComments": true,
    "preserveConstEnums": true,
    "sourceMap": false
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules","**/*.spec.ts"]
}
  1. 在 vue.config.js 中进行设置
configureWebpack: {
  resolve: {extensions: [".ts", ".tsx", ".js", ".json"]},
  module: {
    rules: [
      { test: /\.ts$/, loader: "ts-loader" },
    ]
  }
}