Typescript and Uncaught SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode

Typescript and Uncaught SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode

我有一个包含 class 定义的打字稿文件:

if (window.console == null) {
    (<any>window).console = {
            error: function (a) {
        },
            log: function (a) {
        }
    };
}

class SendMessage {
    //.....
}

编译到 javascript 之后(VS2015),我在 class 定义的行上得到错误:

Uncaught SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode

我发现我必须使用严格模式。但是为什么以及如何在打字稿中使用它?

谢谢

这是因为它正在编译为 ES6,并且浏览器要求在严格模式下使用块作用域声明。

您可以使用严格模式解决此问题。为此添加...

"use strict";

...到每个文件的顶部。

但是,我认为您可能希望将编译目标从 ES6 更改为 ES5。如果您使用的是 tsconfig.json,请将 "target": "es6" 更改为 "target": "es5"。这样做会……编译成 ES5……因此块作用域声明将被适当更改,因此 "use strict"; 将不再需要。此外,更多浏览器将支持您的代码。现在运行时 ES6 支持仍然不广泛。

请注意,如果您不使用 tsconfig.json,您可能需要在项目属性的打字稿构建选项卡中更改目标,如下所示: