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

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

I found that this is the plugin "transform-es2015-modules-commonjs" (in the "es2015" preset ), which adds it.

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

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

+5
source share
1 answer

There are two file processing modes in the ES6 specification:

  • Like a β€œscript,” which will usually be all that we're used to in the standard JS environment

    The syntax of the ES6 module is not allowed, and for backward compatibility reasons, content is only considered strict if it has the "use strict"; directive "use strict"; .

  • Like a "module"

    The syntax of the ES6 module is allowed, and in all cases all the code is strict.

Since the syntax of the ES6 module is related to whether something is a module or a script, and if something is a β€œmodule”, it is automatically strict, Babel uses transform-es2015-modules-commonjs to include both transformations in the same time.

Even if you have to enable only the module conversion itself and exclude strict mode, all the code you wrote is technically invalid, and as soon as you try to use your ES6 code in the real environment of the ES6 module, it would be strict whether you like it or not.

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

+7
source

Source: https://habr.com/ru/post/1238686/


All Articles