为什么选择模块导入不像解构那样工作?

问题描述 投票:0回答:2

我有一个与此类似的文件:

const COLORS = {
  PRIMARY_COLOR: 'red',
  SECONDARY_COLOR: 'green'
};

const APP = {
  APP_COLOR: GRAY_DARK,
  APP_FONT_SIZE: FONT_SIZE_NORMAL,
  APP_FONT_WEIGHT: FONT_WEIGHT_NORMAL,
  APP_SEPARATOR_COLOR: GRAY_LIGHT
};

export default {
  ...COLORS,
  ...APP
};

问题是当我尝试从另一个文件解构该对象时,我得到未定义的值?

import theme, { PRIMARY_COLOR } from '../../../themes/default';

打印主题对象效果很好 但打印 PRIMARY_COLOR 未定义

有什么帮助吗?

javascript ecmascript-6 destructuring
2个回答
1
投票

导入中的

{}
语法用于“命名”导入,而不是解构。

就这样做:

import theme from '../../../themes/default';

const { PRIMARY_COLOR } = theme;

0
投票

要了解它们的区别,首先需要了解它们的导出方式。

如果是

React
,导出过程如下

const Component = ...
...
...
export Component;

这在

React.Component
下可用,您可以像
import { Component } from 'react';

一样导入它

这些在显微镜下看起来是这样的:

default.Component
...

而其他所有内容都位于

default
对象下方。

如果您快速进行

console.log
theme
,您就会明白我的意思。

我希望这是有道理的。


让我们深入一点。

假设您有以下代码:

const a = {
    test: 'hello',
};

const b = {
    foo: 'bar',
}

export default a;

现在,让我们

import
那个

import * as theme from './test.js'

当我们执行

console.log( theme )
时,我们得到

{ default: { test: 'hello' } }

这说明什么?这意味着文件的

export
对象包含
default
属性,当我们执行类似
import theme from 'test'
之类的操作时,该属性会自动加载到内存中。但是,如果您有多个
export
,编译器会为您提供选择的选项,但同时会为您提供一个
default
对象以供回退。

就您而言,您已导出

default
下的所有内容。当你这样做
import theme from './theme'
时,一切都会正常。但是,当您执行
{ PRIMARY_COLOR }...
时,它会尝试找到像

这样导出的内容
export PRIMARY_COLOR...

我希望这能澄清一切! :)

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.