繁体   English   中英

从“默认导出”导入特定对象会导致“未定义”

[英]Importing specific objects from “export default” results in “undefined”

我正在学习Webpack,因此将测试一些我观察到的不同方法。

我创建了以下JS文件,这是我在NPM软件包中观察到的一种导出方法。

// test.js
const Foo = { myVar: "Foo" }
const Bar = { myVar: "Bar"}

export default {
    Foo,
    Bar
}

在我的app.js我写了以下内容:

// app.js
import { Foo } from './test'

console.log(Foo);

我期望从test.js导出对象中获取Foo对象,但在控制台中只是得到一个undefined对象。 另外,Webpack说:

"export 'Foo' was not found in './test'

因此,从导入中删除大括号:

// app.js
import Temp from './test'

console.log(Temp);

这将产生一个包含FooBar对象的对象。

什么是错的,就在这里?

删除默认关键字,该关键字用于指定默认导出内容,而不是所有导出内容。 您当前说的是整个导出对象都是默认对象。

export {
    Foo,
    Bar
}

默认值用于说明是否未指定内容,这应该是默认值,例如:

export {
    Foo as default, // import WhateverIWantToCallIt from './test'
    Foo, // import { Foo } from './test'
    Bar // import { Bar } from './test'
}

// Or you can export things separately:

export function Bar() {...}
export function Foo() {...}
export default Foo; // Declare what the default is

实际上,您导出具有两个参数的对象:

module.exports = {Foo, Bar}

如果import {Foo} from './file'语法中使用import {Foo} from './file'则应分别导出常量

export const Foo = { myVar: "Foo" }
export const Bar = { myVar: "Bar"}

我认为您将销毁与命名导入混为一谈

//this is not destructing but named imports
import { Foo } from './test'


// this is default export. 
export default { Foo, Bar }

为了使用命名的导入,您必须使用命名的导出。

正如其他评论已经解释的那样,您必须使用

default export

// test.js
const Foo = { myVar: "Foo" }
const Bar = { myVar: "Bar"}

export default {
    Foo,
    Bar
}


// app.js
import { Foo } from './test'

console.log(Foo); // works as expected 

暂无
暂无

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

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