Typescript 和 Uncaught SyntaxError:在严格模式之外尚不支持块范围的声明(let、const、function、class)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33634055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:07:22  来源:igfitidea点击:

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

javascripttypescriptvisual-studio-2015uncaught-exception

提问by o..o

I have a typescript file containing a class definition:

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

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

class SendMessage {
    //.....
}

After the compilation to javascript (by VS2015), I get the error on the line with the class definition:

编译为 javascript(通过 VS2015)后,我在类定义行上收到错误:

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

I have found that I have to use the strict mode. But why and how can I use it in typescript?

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

Thanks

谢谢

回答by David Sherret

It's because it's compiling to ES6 and the browser is requiring that block-scoped declarations be used in strict mode.

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

You can fix this by using strict mode. To do that add...

您可以使用严格模式解决此问题。要做到这一点,请添加...

"use strict";

...to the top of every file.

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

However, I think you probably want to change the compilation target from ES6 to ES5. If you are using tsconfig.json, change "target": "es6"to "target": "es5". Doing that will...compile to ES5...and so block-scoped declarations will be changed appropriately so "use strict";will not be required. Additionally, more browsers will support your code. Right now runtime ES6 support is still not widespread.

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

Note that if you are not using tsconfig.json, you might have to change the target in the project properties' typescript build tab as shown here:

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

ECMAScript version change

ECMAScript 版本变更