1

In ES6 javascript I have the following:

import CommonModule from '../../common';
const { Link } = CommonModule.components;

Is there any way to turn this into a 1-liner?

kidcapital
  • 5,064
  • 9
  • 46
  • 68

3 Answers3

3

There is no nested desturcturing in ES6 that I know of. You could do something like:

import { components as C } from '../../common';

// then later

<C.Link>foobar</C.Link>
Chris
  • 54,599
  • 30
  • 149
  • 186
  • 1
    Or simply, `import { components } from ...`. The alias `C` is not mandatory. – Leo Dec 04 '16 at 03:31
  • Is it possible to get a global `Link` like this, to be equivalent to the OP's code? – qxz Dec 04 '16 at 03:33
  • Sure, alias isn't required, but the capital is () won't work. So you would need to do `import { components as Components } from ...` http://stackoverflow.com/questions/30373343/reactjs-component-names-must-begin-with-capital-letters – Chris Dec 04 '16 at 03:58
  • @qxz Not sure I understand? Maybe post a new question? – Chris Dec 04 '16 at 04:00
2

Assuming '../../common' returns a structure along the lines of:

CommonModule = {
  components: {
    Link: {...}
    ...
  }
  ...
}

And you would like to dereference CommonModule.components.Link directly then it's not possible to do so in a one-liner using that syntax.

There is currently no way to dereference deeply nested properties in a single line via the import statement, as the syntax only allows for direct children of the module to be dereferenced.

If you are able to use require instead, then you may use:

const Link = require('../../common').components.Link;

If you would like to keep a reference to CommonModule as well within a one-liner, then you may use:

const {components:{Link}} = CommonModule = require('../../common');

But at this point you're getting to where brevity leads to confusion. What you have in two lines is perfectly understandable, and brief. Less code is not always better.

zzzzBov
  • 174,988
  • 54
  • 320
  • 367
0

You can create index.js file inside common folder and add below code

import Link from './Link';
module.exports = {
  Link: Link
}

(Note:- I don't know exactly Link file path relative to common folder)

Then you can import Link using

import {Link} from '../../common';
maheshiv
  • 1,778
  • 2
  • 17
  • 21