88

If the alternative to:

var Foo = require('foo');

is:

import Foo from 'foo';

What is the alternative to:

var Bar = require('foo').batz

Could it be:

import {batz}  from 'foo' ?
Audwin Oyong
  • 2,247
  • 3
  • 15
  • 32

1 Answers1

61

Nearly. It does however depend on how you are exporting them.

  • named exports (export var batz = …):

    import {batz as Bar} from 'foo';
    
  • default-exported object (export default {batz: …};) - should not be used:

    import Foo from 'foo';
    var Bar = Foo.batz;
    
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 2
    "default-exported object [...] should not be used" – could you explain why not? – Pavlo Jun 17 '15 at 20:14
  • 2
    @Pavlo: Because, as you can see, the import sytax is awkward :-) At least in this case named exports are much more appropriate (I'm not *generally* advising against default exports). – Bergi Jun 17 '15 at 20:16
  • ```import { foo: { batz } } from 'foo'; console.log(batz);``` – Zoltan Nov 25 '15 at 07:23
  • 2
    @szines: Nope, you can only [bind to `BindingIdentifier`s](http://www.ecma-international.org/ecma-262/6.0/#sec-imports), you cannot use destructuring here. – Bergi Nov 25 '15 at 07:29
  • @Bergi Ah thanks. However in Ember.js you can do that what I wrote, probably it is a frameworks specific thing. – Zoltan Nov 25 '15 at 09:17
  • @szines: Or a transpiler extension. Maybe there's an ES7 proposal for it that I don't know of. – Bergi Nov 25 '15 at 09:18
  • what about `var Bar = require('foo').batz()` ? – DragonKnight Jul 06 '23 at 01:34
  • 1
    @DragonKnight see the related [Pass options to ES6 module imports](https://stackoverflow.com/q/29923879/1048572). You need to split that into the import declaration and the statement that actually calls the initialisation function. Typically `import { batz } from 'foo'; const Bar = batz();` – Bergi Jul 06 '23 at 13:13