I think what I am asking for is not possible OOB, but I want to confirm.
We are in a process of upgrading to ES6 (using Babel). Project is a web-site, using AMD (requirejs). I would like to turn a utility module (foolib
) into ES6, but consume it from either ES6 (using import
) or existing ES5/AMD module.
// foolib.es6
export { // as expected, this doesn't work
method1: function () { ... },
value1: 123.456
};
// consumer1.es6
import foolib from "foolib";
// consumer2.js
define(["foolib"], function (foolib) {});
I understand that the solution is to change foolib.es6
as follows:
export function method1() { ... };
export let value1 = 123.456;
However in reality number of entries returned from foolib
is ridiculous. So I was hoping there is a way to export existing object literal without rewriting every line.
Furthermore, I realize that this is most likely impossible, due to the differences between AMD import (using define
) and import
mechanism (later works with exports
object that has values hanging off of it, including default
value, while former expects a single value to be returned).
One possible solution that I think might work is to export my object as default
from foolib.es6
, and then tweak requirejs default loader to inspect imported value for being an esModule and return default value: value && value.__esModule && value.default || value
. Should this work? (I'm still hoping there is an easier solution).
The syntax you are using to export the object is invalid because you are not giving the object a name, so it cannot be a named export, and you are not specifying that it is the default export, so it cannot be the default export. Change it to be the default export:
// foolib.es6
export default {
method1: function () {},
value1: 123.456
}
// consumer.es6
import foolib from "foolib";
console.log(foolib.value) //=> 123.456
You can use the babel-plugin-add-module-exports
Babel plugin to reinstate a default export as the value of module.exports
in Node-land.
And as you discovered, make sure you include this plugin before any other -modules-
plugins, for example transform-es2015-modules-amd
.