2

Isn't ES6 replacing node require()? I've got the following code:

var sprintf = require("sprintf-js").sprintf;

This works as advertised. I can just use sprintf(). I'd like to accomplish the same using ES6 import statements:

import sprintf from 'sprintf-js';

This does not work. Why not? How can I fix it? Bonus points if you can explain how the exports work inside sprintf-js.

raarts
  • 2,711
  • 4
  • 25
  • 45

1 Answers1

7

You can access module exports in a number of ways. See the MDN article.

import defaultMember from "module-name";
import * as name from "module-name";
import { member } from "module-name";
import { member as alias } from "module-name";
import { member1 , member2 } from "module-name";
import { member1 , member2 as alias2 , [...] } from "module-name";
import defaultMember, { member [ , [...] ] } from "module-name";
import defaultMember, * as name from "module-name";
import "module-name";

In this case, your syntax would work if you had assigned the export of sprintf to be default; if you had assigned sprintf to the default object.

Assuming its not, a correct syntax would incorporate references to the exported method within curly-braces.

import { sprintf } from 'sprintf-js';
Bosworth99
  • 4,206
  • 5
  • 37
  • 52
  • 1
    *"would incorporate a destructured object referencing the method"* Note that the syntax used in `import` statements has nothing to do with destructuring. It only looks similar. Just to prevent any confusion. – Felix Kling Mar 12 '16 at 23:11
  • Ah. Interesting point. I might have the wrong impression about the curlybrace syntax on imports. I thought that an equivalent import would be like `import { prop : prop } from 'resource'`, but it clearly doesn't work. – Bosworth99 Mar 12 '16 at 23:19
  • good discussion curly brace syntax on import: http://stackoverflow.com/questions/31096597/using-brackets-with-javascript-import-syntax – Bosworth99 Mar 12 '16 at 23:24
  • 1
    The sprintf-js module is not mine, so I could not modify it, but your solution works. I should have thought of that myself. Thanks. – raarts Mar 13 '16 at 12:53