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: '/',
},
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
?
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./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
?
- Possible duplicate of module.exports vs. export default in Node.js and ES6 – nilobarp Commented Dec 2, 2017 at 6:31
2 Answers
Reset to default 3While 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.
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.