为什么"transform-es2015-modules-commonjs"添加“使用严格"在通天塔6中? [英] Why does "transform-es2015-modules-commonjs" add "use strict" in Babel 6?

查看:616
本文介绍了为什么"transform-es2015-modules-commonjs"添加“使用严格"在通天塔6中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Babel 6,我尝试在已编译的代码中包含"use strict".

我发现它是"transform-es2015-modules- commonjs"插件(在"es2015"预设中)添加它.

似乎没有源代码,如果我删除它,它仍然可以正常工作,即它将import "…"编译为require(…)而没有添加"use strict"./p>

那么,为什么"transform-es2015-modules-commonjs" 强制严格模式?

解决方案

在ES6规范中,可以使用两种模式处理文件:

  1. 作为脚本";通常这就是我们在标准JS环境中习惯的一切

    不允许使用ES6模块语法,并且出于向后兼容的原因,仅当内容的前缀指令为"use strict";时,内容才被视为严格.

  2. 作为模块"

    允许使用ES6模块语法,并且在任何情况下,所有代码都将自动变为严格模式.

因为ES6模块语法与某物是模块还是脚本,以及某物是模块"有关.它是自动严格的,Babel使用transform-es2015-modules-commonjs的存在来同时启用两个转换.

即使您仅启用模块本身的转换并排除严格模式,您编写的所有代码在技术上也将无效,并且,一旦您尝试在真实的ES6模块环境中使用ES6代码,是否严格你喜欢与否.

如果您不希望代码严格,我建议禁用transform-es2015-modules-commonjs转换并使用CommonJS模块,因为它们没有严格的模式要求.

Using Babel 6, I'm trying not to have "use strict" in my compiled code.

I've found that it's the "transform-es2015-modules-commonjs" plugin (in "es2015" preset) which is what adds it.

In the source-code it seems to inherit "babel-plugin-transform-strict-mode", which if I remove it, it still works fine, i.e. it compiles the import "…" into require(…) without adding the "use strict".

So why does "transform-es2015-modules-commonjs" force strict mode?

解决方案

In the ES6 specification, there are two modes in which a file can be processed:

  1. As a "script" which would generally be everything we are accustomed to in a standard JS environment

    ES6 module syntax is not allowed, and for backward-compatibility reasons, content is only treated as strict if it has a prefix directive of "use strict";.

  2. As a "module"

    ES6 module syntax is allowed, and all code is automatically strict mode in all cases.

Because ES6 module syntax is tied up with whether something is a module or a script, and if something is a "module" it is automatically strict, Babel uses the presences of transform-es2015-modules-commonjs to enable both transformations at the same time.

Even if you were to enable just the module transformation itself and exclude strict mode, all code you write would technically be invalid and as soon as you tried to use your ES6 code in a real ES6 module environment, it would be strict whether you like it or not.

If you do not wish your code to be strict, I would suggest disabling the transform-es2015-modules-commonjs transform and using CommonJS modules, since they have no such strict-mode requirement.

这篇关于为什么"transform-es2015-modules-commonjs"添加“使用严格"在通天塔6中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆