为什么在许多文件中存在顶级 const 或 let 时 Typescript 会出错 Node.js

Why does Typescript error when there is a top level const or let with the same name in many files with Node.js

为什么在顶层声明 constlet 会导致 TS2451 错误(见下文)?我知道在浏览器中所有脚本都共享顶级范围,但我正在为 Node.js 编写所有 modules are wrapped.

a.ts:

let lme = 'A';
const cme = 'A';
var me = 'a';

b.js:

let lme = 'A';
const cme = 'A';
var me = 'a';

tsconfig.json:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es6",
        "noImplicitAny": false,
        "sourceMap": false
    },
    "exclude": [
        "node_modules"
    ]
}

输出:

$ tsc
a.ts(3,5): error TS2451: Cannot redeclare block-scoped variable 'lme'.
a.ts(4,7): error TS2451: Cannot redeclare block-scoped variable 'cme'.
b.ts(3,5): error TS2451: Cannot redeclare block-scoped variable 'lme'.
b.ts(4,7): error TS2451: Cannot redeclare block-scoped variable 'cme'.

上下文:

$ tsc --version
Version 1.8.10
$ node --version
v6.5.0

我最初是在尝试将多个文件从 .js 移植到 .ts 时遇到这个问题的,其中有 const fs = require('fs');。我原以为最基本的东西只能在为 Node.js.

编写的 tsjs 之间工作

编译器不会将您的 .ts 文件视为模块,除非文件中有 (used) 导入或导出。
因此,它抱怨变量的重新声明。

例如:

const A = 3;

编译成

var A = 3;

同时

import * as Utils from "./utils"

const A = 3 * Utils.A;

编译成

"use strict";
var Utils = require("./utils");
var A = 3 * Utils.A;

没有 import/export 编译器就不会将其视为模块。


编辑

你可以使用require语法,你只需要引用节点定义:

/// <reference path="./node.d.ts" />
const Utils = require("./utils")