18

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?

lilbumblebear
  • 67
  • 1
  • 7
gotbahn
  • 466
  • 2
  • 4
  • 18
  • why does the first case work? It should not work in general. The names of things matter and you need to know them. – mathtick Dec 30 '20 at 15:06

2 Answers2

36

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

lyschoening
  • 18,170
  • 11
  • 44
  • 54
  • 1
    `import {xxx}` requires a named export (`export xxx`). OP uses default import ([*ImportedDefaultBinding*](http://www.ecma-international.org/ecma-262/6.0/#sec-imports)) in `import foo from 'bar'` so this won't work. See my answer. – Amit Aug 03 '15 at 09:43
5

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'

Amit
  • 45,440
  • 9
  • 78
  • 110