Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using destructuring and renaming with import

I'm currently building a bot for Slack using the node-slack-sdk. In their examples they got the following line:

var CLIENT_EVENTS = require('@slack/client').CLIENT_EVENTS;

The CLIENT_EVENTS is then used as follow:

rtm.on(CLIENT_EVENTS.RTM.AUTHENTICATED, function handleRTMAuthenticated() {
  console.log('RTM client authenticated!');
});

I've changed the require in order to use destructuring to directly get the CLIENT_EVENTS.RTM object that I renamed RTM_CLIENT_EVENTS.

const {
  CLIENT_EVENTS: { RTM: RTM_CLIENT_EVENTS },
} = require('@slack/client');

Now, I wanted to change the require to an import:

import {
  CLIENT_EVENTS: { RTM: RTM_CLIENT_EVENTS },
}  from '@slack/client';

But I got the following error:

ES2015 named imports do not destructure. Use another statement for destructuring after the import

Any idea why they don't destructure?

like image 467
Erazihel Avatar asked Jul 13 '17 12:07

Erazihel


People also ask

How do you Destructure an object in typescript?

And this is destructuring an object. Let's take the following example: const user = { firstname: 'Chris', lastname: 'Bongers', age: 32 }; const { firstname, age } = user; By using this destructuring, we extract specific properties from an object.

How do you Destructure an array in JavaScript?

To destructure an array in JavaScript, we use the square brackets [] to store the variable name which will be assigned to the name of the array storing the element. const [var1, var2, ...]

Can I use object Destructuring?

You can use the object destructuring assignment to swap the values of two or more different variables. The snippet above used direct object destructuring to reassign the firstName and website variables with the values of the object literal on the right-hand side of the assignment operator.


2 Answers

import has strict syntax that only mimics shallow destructuring syntax but is supposed to be statically analyzed. So does export, it mimics object literal syntax.

As the error suggests, the proper way to do this is

import { CLIENT_EVENTS }  from '@slack/client';

const { RTM: RTM_CLIENT_EVENTS } = CLIENT_EVENTS;
like image 181
Estus Flask Avatar answered Oct 19 '22 19:10

Estus Flask


The import statement in javascript does not natively support the destructuring syntax. But you can rename the imports in the following ways:

import {RTM_CLIENT_EVENTS as RTM} from '@slack/client'

Here the RTM_CLIENT_EVENTS propery will be imported and renamed to RTM using the as keyword.

like image 6
Aditya Tripathi Avatar answered Oct 19 '22 17:10

Aditya Tripathi