Skip to content

Instantly share code, notes, and snippets.

@wycats
Last active December 31, 2015 11:59
Show Gist options
  • Select an option

  • Save wycats/7983305 to your computer and use it in GitHub Desktop.

Select an option

Save wycats/7983305 to your computer and use it in GitHub Desktop.
// A. Create a new object that will contain the names ES6 module exports. We create it immediately so that
// it will work across cycles.
var es6Out = {};
// B. Assign it immediately to module.exports so other files that try to require this file will see it
// right away.
module.exports = {
__es6_module__: es6Out
};
// C. Require another module, and check to see whether it has an ES6 module on it. Because the other module
// also created its ES6 module eagerly, this module will be able to get a handle on an empty copy of the
// soon-to-be-filled-in ES6 modules in the cycle case.
var _b = require("./b"), es6Module = _b.__es6_module__, b;
// D. If we find an ES6 module, save it off for future use. Otherwise, use the regular node module.
if (es6Module) {
b = es6Module;
} else {
b = _b;
}
var exports = function() {
// E. Rewrite bindings that came off of `import` statements to lazily get their values from the module.
console.log("In a. bar = " + b.bar);
};
var foo = 'foo';
// F. Fill in the ES6 module, including default export to point at the exports function.
es6Out.default = exports;
es6Out.foo = foo;
// G. Stick the ES6 module onto the standard-looking node export.
exports.__es6_module__ = es6Out;
// H. Replace the temporary module.exports with the standard-looking node export.
module.exports = exports;
// This works the same way as the description in a.js
var es6Out = {};
module.exports = {
__es6_module__: es6Out
};
var _a = require("./a"), es6Module = _a.__es6_module__, a;
if (es6Module) {
a = es6Module;
} else {
a = _a;
}
var exports = function() {
console.log('In b. foo = ' + a.foo);
};
var bar = 'bar';
es6Out.default = exports;
es6Out.bar = bar;
exports.__es6_module__ = es6Out;
module.exports = exports;
var a = require("./a");
var b = require("./b");
a();
b();
/**
Output
In a. bar = bar
In b. foo = foo
*/
@joliss

joliss commented Dec 17, 2013

Copy link
Copy Markdown

If we want to make regular Node module objects available as the default import (see my comment), we'd presumably be doing this:

--- a/a.js
+++ b/a.js
@@ -18,7 +18,7 @@ var _b = require("./b"), es6Module = _b.__es6_module__, b;
 if (es6Module) {
   b = es6Module;
 } else {
-  b = _b;
+  b = { 'default': _b };
 }

 var exports = function() {

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment