Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How change require to import with key in ES6? [duplicate]

I want to write require with ES6 import. In the case without a key, it is pretty easy to do:

var args2 = require('yargs2'); -> import foo from 'bar';

But with a key, I can't find the appropriate syntax:

var foo = require('bar').key;

How can I do that?

like image 365
gotbahn Avatar asked Aug 03 '15 06:08

gotbahn


2 Answers

The syntax for importing a member of a module with an aliased name is:

import {key as foo} from 'bar';

This is equivalent to var foo = require('bar').key;

If you want to import a member without aliasing it, the syntax is simpler:

import {foo} from 'bar';

Is equivalent to:

 var foo = require('bar').foo;

MDN article about the import statement

like image 199
lyschoening Avatar answered Sep 17 '22 15:09

lyschoening


var foo = require('bar').key is identical to var bar = require('bar'); var foo = bar.key (other then the declaration of a 'bar' variable that is probably no longer needed).

if you export an object that has a property named 'key', that would be the same in ES6 import/export.

import bar from 'bar';
var foo = bar.key;

Note This assumes a default export (export default xxx) as in OP. If using a named export (export foo), the syntax to use is import {foo} from 'bar'

like image 43
Amit Avatar answered Sep 21 '22 15:09

Amit