0

In the React project I found this piece of code, which is pretty much standard:

import React from 'react';

import {
    ImageLeft,
    ImageRight,
    ImageBottom,
    ImageBanner    
} from './content';

const LAYOUT_COMPONENT = {   
    image_left: ImageLeft,
    image_right: ImageRight,
    image_bottom: ImageBottom,
    image_banner: ImageBanner    
};

LAYOUT_COMPONENT object has repetitions. Is it possible somehow to create it with destructuring from import statement, in order to avoid extra code?

Amiga500
  • 5,874
  • 10
  • 64
  • 117
  • Well, you could name them the same so you could do: `const LAYOUT_COMPONENT = {ImageLeft, ImageRight, etc etc. }` as you probably know this is the same as `const LAYOUT_COMPONENT = {ImageLeft: ImageLeft, ImageRight: ImageRight, etc etc. }` but outside of that I wouldn't change it - you need some separation – StudioTime Aug 04 '17 at 10:16
  • does `./content` component contains more properties other than you mentioned while importing? – Anurag Aug 04 '17 at 10:24
  • content is a folder that has other components that are exported by their name. And I import all of them. There are more props (files), but I ommited them for clarity. – Amiga500 Aug 04 '17 at 11:19

1 Answers1

1

No, there is no destructuring in import statements.

What you could do is

import * as contents from './content';

const LAYOUT_COMPONENT = {};
for (let p of ["Left", "Right", "Bottom", "Banner"])
    LAYOUT_COMPONENT["image_"+p.toLowerCase()] = contents["Image"+p];
}

but notice this will prevent a module bundler from tree shaking.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375