重写 vscode-file-templates-ext

2018-05-13  本文已影响14人  一半晴天

在 VSCode 找文件模板插件时发现了此插件。想来功能不是很复杂,于是 Fork 了一份用来学习修改。地址如下:
vscode-file-templates-ext
整个重构部分分为两大块。一个是项目配置的更新,一个是代码的重构。

项目配置更新

由于原仓库已经 2年没有更新(因为原来的功能确实已经够用了。),不过我作为新学,还是想着先把配置更新一下。

  1. .vscode/launch.json 根据最新生成的 Hello World 中的配置,将原来的配置修改一下。

  2. .vscode/tasks.json 同上。

  3. tsconfig.json 中的配置更新。
    主要更新 targetes6 增加对 es6 库的依赖。rootDir 改为 src

"compilerOptions": {
        "module": "commonjs",
        "target": "es6",
        "lib": [
            "es6"
        ],
        "outDir": "out",
        "sourceMap": true,
        "rootDir": "src"
    },
  1. 相应的将原来的 tests 目录移到 src 目录。

  2. 相应的将 package.json 中的 main 入口改为 "main": "./out/extension",

  3. 参照新插件项目的配置,更新 package.json 中的 scripts 配置:

 "scripts": {
    "lint": "tslint -c tslint.json src/**/*.ts",
    "vscode:prepublish": "npm run compile",
    "compile": "tsc -p ./",
    "watch": "tsc -watch -p ./",
    "postinstall": "node ./node_modules/vscode/bin/install"
  },
  1. 更新依赖,增加 fs-extra 依赖。

  2. 删除原项目中的 types 目录,改为在依赖上添加

    "@types/mocha": "^2.2.42",
    "@types/node": "^7.0.43",
  1. 因为后面要用到 async/await 的语法支持。所以也提高了对 vscode.engines 版本的依赖:
  "engines": {
    "vscode": "^1.18.0"
  },

代码重构。

将函数改为类

原来的插件逻辑的主要代码是在一个单一的函数中的。 为了方便拆分函数。还是按类来组织比较好,所以后面提取成了类。

将原来的 Thenable 方法的回调,及 fs 异步写法使用 async/await 改写。

重构之后代码清晰更好看一些了。当然这主要是 async/await 的功劳。

重构前代码见:
https://github.com/banxi1988/vscode-file-templates-ext/tree/1.2.0

重构后代码见:
https://github.com/banxi1988/vscode-file-templates-ext/commit/c96bf7a784d6e65032fd62a1ce5b184f4365bb5b

上一篇下一篇

猜你喜欢

热点阅读