Why does “transform-es2015-modules-commonjs” add “use strict” in Babel 6?

眉间皱痕 提交于 2020-01-02 03:59:45

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/34366875/why-does-transform-es2015-modules-commonjs-add-use-strict-in-babel-6

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!