Babel CommonJS -> ES Deferred Execution Wrapper Format
This plugin implements a deferred execution wodule format that allows supporting CommonJS execution semantics through an ES modules protocol.
Modules converted in this way can only import from other modules converted to this format.
This project aims for accuracy and reliability transforming a tree of CommonJS modules into a spec-compliant tree of ES Modules.
Output:
;;var exports = {};var module = { return exports; } { exports = _exports; }; { if executed return moduleexports; executed = true; __dew__ = null; module {}; exportsblah = 'hi'; var a = y; var b = depB; return moduleexports;}
To import a CommonJS module tree converted via the above into an ES module, the following execution wrapper is required:
x.js
;;
As well as execution wrapping, the following code transformations are handled:
- Simple 'use strict' code conversion if not already strict.
- Defines the
exports
andmodule
variables in module scope. - Any use of
global
orGLOBAL
defines global in the module scope. - Top-level
this
is replaced with anexports
reference. - Top-level
return
is adjusted to always ensure a falsy return value. - Internal
this
references that are not direct calls, fallback to _global. - Implicit globals of the form
globalName = ...
are rescoped for a simple strict module conversion. - Use of
Buffer
andprocess
is transformed into an import ofbuffer
orprocess
. This module name can be customized by themap
configuration option.
The remaining strict conversion cases that don't convert are then just the edge cases of loose -> strict mode conversion:
- Any use of
with
statements will throw - Multiple duplicate function parameters
- Relying on dynamic arguments
- Assigning to reserved names
- Using eval to define variables
- Expecting
this
being the global as the default context for function calls delete
statements of local variables are removed
The above should comprehensively cover the failure cases.
License
MIT