ES6 equivalent Node.js requires function call

What is the shortest ES6 equivalent of calling a require function below?

 module.exports = function(app) {...}; require('./routes')(app); 

In other words, is there a single layer equivalent in ES6 modules?

+5
source share
1 answer

I just started to delve into ES6, but I think it will be something like:

 import * as routes from './routes'; 

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

This can then be used immediately as follows:

 import * as routes from './routes'; doAThing( routes.myVar, routes.myMethod() ); 

If a module has only one named export, it still saves two lines, and then calls:

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

This is the same for any export quantity:

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

It is better to import as described above:

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

I used the โ€œrecommendedโ€ format this Axel Rauschmayer post related to ES6 modules, but depending on which module exports your import statement, it may look different:

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

I find this (1 line for import, 1 line for calling) the syntax is transparent and readable, so I like it. For some, this may seem unsuccessful. However, the bottom line says that there is not a single import / invoke line in ES6

+5
source

Source: https://habr.com/ru/post/1239373/


All Articles