简体   繁体   English

Javascript 导出默认和导入

[英]Javascript export default and import

I have the following code:我有以下代码:

const API1 = new API({
   ...
})

const API2 = new API({
   ...
})

export default { API1, API2 }

I need to import like this:我需要像这样导入:

import API1 from '/lib/api'

API1.get()...

But it doesn't work.但它不起作用。 I don't want to do this:我不想这样做:

import blah from '/lib/api'
blah.API1.get()...

How can I solve this?我该如何解决这个问题? Thanks.谢谢。

If you need to export multiple items, and don't want to have to create two variables in the consuming module (one for the default import - the object, and another for the API1 property), your only other option is to change the default export to a named export, allowing you to import just one particular named property:如果您需要导出多个项目,并且不想在消费模块中创建两个变量(一个用于默认导入 - object,另一个用于API1属性),您唯一的其他选择是更改默认值导出到命名导出,允许您导入一个特定的命名属性:

const API1 = new API({
   ...
})

const API2 = new API({
   ...
})

export { API1, API2 }

and

import { API1 } from '/lib/api'

API1.get()...

The export { syntax indicates that the export is named, rather than default, and the import { syntax indicates that you're importing a named import, rather than a default import. export {语法表示导出是命名的,而不是默认的, import {语法表示您正在导入命名的导入,而不是默认的导入。

(It looks a lot like destructuring, and it's a little bit similar, but it's not the same) (看起来很像解构,也有点像,但又不一样)

Since you're default exporting an object you need to access individual property to access there methods, Instead you can use named exports由于您默认导出 object 您需要访问单个属性才能访问那里的方法,而是可以使用命名导出

// exporting values

export const API1 = new API({
   ...
})

export const API2 = new API({
   ...
})

// Importing values

import { API1 } from '/lib/api'

API1.get()...

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

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