2

I've been struggling to destruct my mongo object in another file, my object structure is like below.

  const env = {
       project: 'CRIBBBLE BACKEND',
       url: 'localhost',
       api: {
         url: 'https://api.dribbble.com/v1/',
       },
       port: parseInt(process.env.PORT, 10) || 3000,
       mongo: database,
};

 export default env;

But when I'm trying to import the mongo object in another js file like this { mongo } from 'config' the returned value is undefined. But if I change the export default value to module.exports it works as its expected.

So, I'm just wondering what is the difference between module.exports and export default?

Pedram marandi
  • 1,474
  • 1
  • 19
  • 35
  • Possible duplicate of [module.exports vs. export default in Node.js and ES6](https://stackoverflow.com/questions/40294870/module-exports-vs-export-default-in-node-js-and-es6) – nilobarp Dec 02 '17 at 06:31

2 Answers2

3

module.exports is a NodeJS (CommonJS) style of importing and exporting from different files. import/export is ES6 feature of doing the same thing.

If you export defualt you need to import it like import env from 'location'(Look I emit the {} part) and then access the mongo via env.mongo. You can't just get the mongo object directly.

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
3

While you export using export default foo the whole exported foo is available using {default: foo} after import. That's why you cannot access properties you want. Try to import as: import * as bar from './foo' and explore the bar using console.log(bar) to see what's happening underneath. Also for more info have a look: es6 module exports on 2ality.com

Javad M. Amiri
  • 594
  • 5
  • 20