简体   繁体   English

销毁导出默认值和module.exports之间的区别

[英]Difference between destructing export default and module.exports

I've been struggling to destruct my mongo object in another file, my object structure is like below. 我一直在努力将mongo对象破坏到另一个文件中,我的对象结构如下所示。

  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 . 但是,当我试图{ mongo } from 'config'中将mongo对象import到另一个js文件,例如{ mongo } from 'config'返回的值是undefined But if I change the export default value to module.exports it works as its expected. 但是,如果我将导出默认值更改为module.exports它将按预期工作。

So, I'm just wondering what is the difference between module.exports and export default ? 所以,我只是想知道module.exportsexport default之间有什么区别?

module.exports is a NodeJS ( CommonJS ) style of importing and exporting from different files. module.exports是从不同文件导入和导出的module.exportsCommonJS )样式。 import/export is ES6 feature of doing the same thing. import/export是执行相同操作的ES6功能。

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 . 如果要export defualt ,则需要像import env from 'location'一样导入它(看起来我发出{}部分),然后通过env.mongo访问mongo You can't just get the mongo object directly. 您不能直接获取mongo对象。

While you export using export default foo the whole exported foo is available using {default: foo} after import. 使用export default foo导出时,导入后使用{default: foo}可使用整个导出的foo 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. 尝试为进口: import * as bar from './foo'和探索bar使用console.log(bar) ,看看发生了什么下方。 Also for more info have a look: es6 module exports on 2ality.com 还可以查看更多信息: 2ality.com上的es6 模块导出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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