【问题标题】:Importing an Object with SubObjects and Arrays in JavaScript在 JavaScript 中导入带有子对象和数组的对象
【发布时间】:2019-11-13 13:50:06
【问题描述】:

我有一个主题对象,它有许多对象和数组作为值。即,像这样:

export const theme = {
  colors: {...list of colors},
  breakpoints: [...array of breakpoints],
  ...
}

现在,假设我想访问另一个文档中的颜色对象和断点数组。目前,我正在导入这样的主题:

import { theme } from '../../theme'
const { colors, breakpoints: bp } = theme
}

我正在使用breakpoints: bp,以便在我的文件中将breakpoints 别名为bp

我想知道是否可以在 import 语句中完成所有这些操作。即,不是导入整个 theme 对象,而是只导入颜色对象和断点数组。像这样的东西(这个代码不起作用,它只是为了说明这个想法):

import { theme.colors as colors, theme.breakpoints as bp } from '../../theme'

这可能吗?如果有,怎么做?

谢谢。

【问题讨论】:

    标签: javascript ecmascript-6 javascript-import


    【解决方案1】:

    您可能应该更改导出主题的方式。您可以只导出主题的每个属性 - 它就像删除 const 声明并仅导出对象一样简单。 :

    export {
      colors: {...list of colors},
      breakpoints: [...array of breakpoints],
      ...
    }
    

    然后像这样使用导入:

    import { colors, breakpoints as bp } from '../../themes'
    

    【讨论】:

      【解决方案2】:

      我认为不幸的是,import statements 不支持object destructuring

      我找到了解释这个问题的线程

      How to import part of object in ES6 modules

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-06-06
        • 2019-09-27
        • 2020-07-11
        • 1970-01-01
        • 2017-06-28
        • 2017-06-26
        • 2019-03-19
        相关资源
        最近更新 更多