6

What's the shortest ES6 equivalent of require function call below?

module.exports = function(app) {...};

require('./routes')(app);

In other words is there a one-liner equivalent in ES6 modules?

krl
  • 4,452
  • 3
  • 30
  • 52

1 Answers1

5

I've just started to delve into ES6, but I believe that would be something like:

import * as routes from './routes';

...assuming ./routes is an ES6 module exporting something.

This can then be used immediately like so:

import * as routes from './routes';

doAThing( routes.myVar, routes.myMethod() );

If the module has only a single named export, it's still two lines to import, then call:

import { name } from './routes';
name();

This is the same for any number of exports:

import { name1, name2 } from './routes';
name1();
name2();

A better import is as written above:

import * as routes from './routes';
routes.foo();
routes.bar();

I used the "recommended" format from this Axel Rauschmayer post relating to ES6 modules, but depending on what the module exports your import statement may look different:

import * as fs from 'fs'; // recommended

I find this (1 line to import, 1 line to invoke) syntax clear and readable, so I like it. For some, it may seem unfortunate. However, the bottom line is that there is no one line import/invoke in ES6

Community
  • 1
  • 1
rockerest
  • 9,847
  • 3
  • 33
  • 67
  • That's just import. I'm interested in calling the imported function inline. – krl Dec 28 '15 at 20:21
  • 1
    Sorry I misunderstood your question. Let me double check the syntax and see if I can update any further. – rockerest Dec 28 '15 at 20:25
  • Yes, so we get 2 lines in ES6 modules vs 1 line `require('...')()` in Node.js. Is there a one-liner? – krl Dec 28 '15 at 20:30
  • @kyrylkov the `import` statement syntax does not provide any way to use an imported value as part of an expression. All it does is bind the value to a symbol. – Pointy Dec 28 '15 at 20:32
  • @kyrylkov no one-liner. Also I'm not sure if `imports` have to be at the top of files, whereas nodes commonJS you can `require` anywhere in a file. Certainly with babel transpilation you must import early, but I'm not sure if thats a constraint of transpilation or following spec. – Matt Styles Dec 28 '15 at 20:46