Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 equivalent of Node.js require function call [duplicate]

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?

like image 686
krl Avatar asked Dec 28 '15 20:12

krl


People also ask

Does Nodejs support ES6?

Node js doesn't support ES6 import directly. If we try to use import for importing modules directly in node js it will throw out the error. For example, if we try to import express module by writing import express from 'express' node js will throw an error as follows: Node has experimental support for ES modules.

What is require () in JavaScript?

The require() method is used to load and cache JavaScript modules. So, if you want to load a local, relative JavaScript module into a Node. js application, you can simply use the require() method. Example: var yourModule = require( "your_module_name" ); //.js file extension is optional.

Can we use import instead of require in node JS?

You can now start using modern ES Import/Export statements in your Node apps without the need for a tool such as Babel.


1 Answers

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

like image 165
rockerest Avatar answered Sep 19 '22 12:09

rockerest