简体   繁体   中英

export default vs module.exports differences

This works:

import {bar} from './foo';
bar();

// foo.js
module.exports = {
 bar() {}
}

And this works:

import foo from './foo';
foo.bar();

// foo.js
export default {
 bar() {}
}

So why doesn't this work?

import {bar} from './foo';
bar();

// foo.js
export default {
 bar() {}
}

It throws TypeError: (0 , _foo.bar) is not a function .

When you have

export default {
  bar() {}
}

The actual object exported is of the following form:

exports: {
  default: {
    bar() {}
  }
}

When you do a simple import (eg, import foo from './foo'; ) you are actually getting the default object inside the import (ie, exports.default ). This will become apparent when you run babel to compile to ES5.

When you try to import a specific function (eg, import { bar } from './foo'; ), as per your case, you are actually trying to get exports.bar instead of exports.default.bar . Hence why the bar function is undefined.

When you have just multiple exports:

export function foo() {};
export function bar() {};

You will end up having this object:

exports: {
  foo() {},
  bar() {}
}

And thus import { bar } from './foo'; will work. This is the similar case with module.exports you are essentially storing an exports object as above. Hence you can import the bar function.

I hope this is clear enough.

//for your 3rd case this should work

import {default as bar } from './foo';
bar();

// foo.js
export default {
  bar() {}
}

Of course is not working, you exported foo default and imported it with curly braces {} . To keep it simple remember this, if you're exporting the default way you need no curly braces, but if you're importing normaly an module, you'll use curly braces {} to acces a specific function in the module ;). You can see examples here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM