Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

es6 import 'destructuring' not working

Tags:

ecmascript-6

Hey there I have this uiTypes.js file like this:

export default {
  SELECT_ITEM: 'SELECT_ITEM',
  DESELECT_ITEM: 'DESELECT_ITEM',
  TOGGLE_ITEM: 'TOGGLE_ITEM',
}

And when I try importing its content like so, it works:

import uiTypes from './uiTypes';
console.log(uiTypes.SELECT_ITEM) // 'SELECT_ITEM'

But not like this:

import { SELECT_ITEM, DESELECT_ITEM, TOGGLE_ITEM } from './uiTypes';
console.log(SELECT_ITEM) // undefined,

Am I missing something?

like image 903
Nik So Avatar asked Apr 07 '16 21:04

Nik So


People also ask

What is ES6 Destructuring?

Destructuring means to break down a complex structure into simpler parts. With the syntax of destructuring, you can extract smaller fragments from objects and arrays. It can be used for assignments and declaration of a variable.

What does Destructuring do exactly when would you use it?

Destructuring is a JavaScript expression that allows us to extract data from arrays, objects, and maps and set them into new, distinct variables. Destructuring allows us to extract multiple properties, or items, from an array​ at a time.

What is advantage of Destructuring in JavaScript?

Advantages of Destructuring:It makes developer's life easy, by assigning their own variables. Nested data is more complex, it takes time to access, but by the use of destructuring, we can access faster of nested data.


1 Answers

There is no destructuring for imports (notice also that exports and imports use the keyword as instead of a colon to avoid confusion with objects). You can either import the default export, individual named exports, or the module namespace object.

Your attempt is trying to import three named exports, while there is only a default export; that's why it's failing.

You should use named exports:

export const SELECT_ITEM = 'SELECT_ITEM';
export const DESELECT_ITEM = 'DESELECT_ITEM';
export const TOGGLE_ITEM = 'TOGGLE_ITEM';

or use "real" destructuring after importing the object:

import uiTypes from './uiTypes';
const {SELECT_ITEM, DESELECT_ITEM, TOGGLE_ITEM} = uiTypes;
like image 79
Bergi Avatar answered Oct 19 '22 14:10

Bergi