全部 / 前端 / 工具 / 技术 · 2022年6月22日 0

Coder Runner 运行 TypeScript

广告位招租 (vx: ghostcode, 备注:网站广告)

默认标题_公众号封面首图_2022-06-22+15_05_02

两种方法:

  1. ts => js

全局安装:

npm install -g typescript

然后在 vscode 的 settings.json 中添加:

// 指定解释器
"code-runner.executorMap": {
    "typescript": "tsc $fileName && node $fileNameWithoutExt.js"
},

它会编译出同名的 JS 文件,然后执行:

  1. 使用 ts-node
npm install -g ts-node

当你运行的时候,会遇到如下错误:

需要在执行的目录创建一个 tsconfig.json 文件且把 dom 添加到 lib 下:

{
    "compilerOptions": {
        "rootDir": "src",
        "outDir": "bin",
        "module": "commonjs",
        "noImplicitAny": false,
        "removeComments": true,
        "preserveConstEnums": true,
        "sourceMap": true,
        "target": "es5",
        "lib": [
            "es6",
            "dom", // 添加 dom 选项
        ],
        "types": [
            "reflect-metadata"
        ],
        "moduleResolution": "node",
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true
    }
}

运行成功: