javascriptecmascript-6importdestructuring

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?


Solution

  • 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;