Can I use alias with NodeJS require function?

Javascriptnode.jsEcmascript 6Commonjs

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

Sure, just use the object destructuring syntax:

 const { old_name: new_name, foo: f, bar: b } = require('module');

Solution 2 - Javascript

It is possible (tested with Node 8.9.4):

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

Solution 3 - Javascript

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();

Solution 4 - Javascript

I would say it is not possible, but an alternative would be:

const m = require('module');
const f = m.foo;
const b = m.bar;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionxMortView Question on Stackoverflow
Solution 1 - JavascriptJonas WilmsView Answer on Stackoverflow
Solution 2 - JavascriptbarnskiView Answer on Stackoverflow
Solution 3 - JavascriptclusterBuddyView Answer on Stackoverflow
Solution 4 - JavascriptRafael PaulinoView Answer on Stackoverflow