标签云

微信群

扫码加入我们

WeChat QR Code

I have an ES6 class defined in an ES6 module that exports an instance of that class:class MyObject {constructor() {this.propertyA = 1;this.propertyB = 2;}myMethod() {doStuff();}}var theInstance = new MyObject();export default theInstance;When I import this module, myMethod is undefined:import * as theObject from './my/module';theObject.myMethod(); // Error! undefined is not a method.The properties defined in the constructor do exist. It's as though the object's prototype was excluded, and only its members were exported.I am requiring 'babel/register'.Why is exporting this object not working correctly?


Strangely enough, exporting an instance of new solved my problem. I had been trying to export the class definition, and instantiate new in the "importer" file. That gave me the error. But exporting new, it worked! Your problem, my solution. shrug

2019年04月19日34分55秒

Yes. import x from '...' imports the default export. And that's what you have (export default new MyObject()). import * as x from '...' imports all named exports as properties of an object. You can import a subset via import {foo, bar} from '...'. Named export are of the form export function foo() {} or export var bar = ...; or export {abc, xyz}.

2019年04月18日34分55秒

Maybe it's just a babel thing, but apparently import *, if you had an export default, imports immediate properties of the default object. Do you know if that's the official behavior or if that's just part of how babel transpiles?

2019年04月19日34分55秒

Do you mean import * from 'something'? That is actually invalid. Here are the valid declarations: ecma-international.org/ecma-262/6.0/index.html#table-40

2019年04月19日34分55秒

No, I mean import * as foo from 'something' like I had originally tried.

2019年04月18日34分55秒

That should not happen, although it might be due to interoperability between ES6 modules and CommonJS modules.

2019年04月19日34分55秒