0

My code has various imports that I use exactly once.

I can bind an import to a variable, then use it like so:

module.js

export default 'hello';

main.js

import greeting from './module.js';
console.log(greeting);

But if I have many imports, I have to think of many arbitrary variable names.

Is there a way to use the import, yet skip the creation of this variable greeting? The kind of thing that I have in mind is something like this:

console.log(import './module.js';);

But that particular syntax does not exist (at least, Babel interprets this as a SyntaxError: Unexpected token at console.log(i…). Is there a way to do this in ES6?

Birchlabs
  • 7,437
  • 5
  • 35
  • 54
  • If you have named exports, you can do `import * as allExports from './module';`. – Felix Kling Nov 21 '16 at 14:43
  • FWIW: It's the other way round. `import greeting` is not an assignment, it creates a binding. – a better oliver Nov 21 '16 at 15:18
  • @zeroflagL hm, looks like I've been misled in my education. I'd convinced myself that assignment was where you create variables, and binding was where you did not. I've corrected the wording of the question in light of your clarification. – Birchlabs Nov 21 '16 at 15:36
  • See also [Pass options to ES6 module imports](http://stackoverflow.com/q/29923879/1048572): no, it's impossible to import anything without giving it a name, unless you use the loader interface directly. – Bergi Nov 21 '16 at 21:43
  • "*I have to think of many arbitrary variable names*" - why, are your modules arbitrary as well? How exactly do you need to use them ("once")? Maybe modules are the wrong tool for your job? – Bergi Nov 21 '16 at 21:44

1 Answers1

0

You can't do console.log(import './module.js') because the import statement is not an expression.

If you have many imports, maybe you should put the exported values together in one module and use named exports, like that:

module.js:

export const firstGreeting = 'hello';
export const secondGreeting = 'hi';
export const thirdGreeting = 'howdy';

main.js:

import {firstGreeting, secondGreeting, thirdGreeting} from './module';

console.log(firstGreeting);
console.log(secondGreeting);
console.log(thirdGreeting);
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
  • import {firstGreeting, secondGreeting, thirdGreeting} from './module'; – Raja Sekar Nov 21 '16 at 14:37
  • Thanks for clarifying that `import` statements are not expressions. That explains why my attempted syntax failed with a syntax error. As you know: the additional tip you provide is not applicable to my situation; all of my modules use a single, default export. Moving to a multiple, named export just moves the "naming everything" problem to the _export_ stage. – Birchlabs Nov 21 '16 at 14:55
  • 1
    @Birchlabs Well it seems that you can't avoid naming your exports. – Michał Perłakowski Nov 21 '16 at 15:00