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.

1
  • You probably need to do import { sprintf } from 'sprintf-js'; Commented Mar 12, 2016 at 23:02

1 Answer 1

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';
Sign up to request clarification or add additional context in comments.

4 Comments

"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.
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.
good discussion curly brace syntax on import: stackoverflow.com/questions/31096597/…
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.