Can I use alias with NodeJS require function?

40,832

Solution 1

Sure, just use the object destructuring syntax:

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

Solution 2

It is possible (tested with Node 8.9.4):

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

Solution 3

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

Share:
40,832
xMort
Author by

xMort

Senior Software Engineer at GoodData Corporation

Updated on July 08, 2022

Comments

  • xMort
    xMort almost 2 years

    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?

  • xMort
    xMort about 6 years
    Great! I should have thought about it.
  • technogeek1995
    technogeek1995 about 5 years
    For clarification: const { prevName: newName } = require('../package.json'); I flipped it around and couldn't figure out why it didn't work for a couple minutes.
  • Nahum
    Nahum over 4 years
    @technogeek1995 you are the real MVP. logged in to SO to thank you!
  • Beau
    Beau over 3 years
    If you're requiring a default export (something like export default foo;), "default" is the name so you'd do: const { default: newName } = require('module');
  • tugrul
    tugrul about 2 years
    There is a little confusion. emitter variable is not alias of EventEmitter. It presents entire module. Testable code is const events = {EventEmitter} = require('events'); assert(events.EventEmitter === EventEmitter);