Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use alias with NodeJS require function?

I have an ES6 module that exports two constants:

export const foo = "foo";
export const bar = "bar";

I can do the following in another module:

import { foo as f, bar as b } from 'module';
console.log(`${f} ${b}`); // foo bar

When I use NodeJS modules, I would have written it like this:

module.exports.foo = "foo";
module.exports.bar = "bar";

Now when I use it in another module can I somehow rename the imported variables as with ES6 modules?

const { foo as f, bar as b } = require('module'); // invalid syntax
console.log(`${f} ${b}`); // foo bar

How can I rename the imported constants in NodeJS modules?

like image 693
xMort Avatar asked Feb 23 '18 16:02

xMort


People also ask

For what require () is used in NodeJS?

1) require() In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.

Can I use both require and import in NodeJS?

Cases where it is necessary to use both “require” and “import” in a single file, are quite rare and it is generally not recommended and considered not a good practice. However, sometimes it is the easiest way for us to solve a problem. There are always trade-offs and the decision is up to you.

Is NodeJS require synchronous or asynchronous?

NodeJS is an asynchronous event-driven JavaScript runtime environment designed to build scalable network applications. Asynchronous here refers to all those functions in JavaScript that are processed in the background without blocking any other request.


3 Answers

Sure, just use the object destructuring syntax:

 const { old_name: new_name, foo: f, bar: b } = require('module');
like image 86
Jonas Wilms Avatar answered Oct 17 '22 10:10

Jonas Wilms


It is possible (tested with Node 8.9.4):

const {foo: f, bar: b} = require('module');
console.log(`${f} ${b}`); // foo bar
like image 15
barnski Avatar answered Oct 17 '22 09:10

barnski


Yes, a simple destructure would adhere to your request.

Instead of:

var events = require('events');
var emitter = new events.EventEmitter();

You can write:

const emitter = {EventEmitter} = require('events');

emitter() will alias the method EventEmitter()

Just remember to instantiate your named function: var e = new emitter(); 😁

like image 4
clusterBuddy Avatar answered Oct 17 '22 10:10

clusterBuddy