Moshe
Moshe

Reputation: 6987

Importing an Object with SubObjects and Arrays in JavaScript

I have a theme object that has a number of objects and arrays as values. I.e., something like this:

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

Now, let's say I want to access the color object and breakpoints array in another document. Currently, I am importing theme like this:

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

I am using breakpoints: bp so that I can alias breakpoints as bp in my file.

What I am wondering is whether or not it is possible to do all this in the import statement. I.e., instead of importing the entire theme object, to import just the color object and breakpoint array. Something like this (this code does NOT works, it's just to illustrate the idea):

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

Is this possible? If so, how?

Thanks.

Upvotes: 2

Views: 396

Answers (2)

Dario García moya
Dario García moya

Reputation: 132

I think that unfortunately, the import statements do not support the object destructuring.

I found this thread where this question was explained

How to import part of object in ES6 modules

Upvotes: 0

Kobe
Kobe

Reputation: 6446

It might be that you should change the way you export the theme. You could just export each property of theme - it's as simple as removing the const declaration and just exporting the object. :

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

and then using import as such:

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

Upvotes: 1

Related Questions