101

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
  • 1,545
  • 3
  • 11
  • 20
  • `foo` isn't exported directly, it's a property of `exports` (which I'm presuming `module` gets exported?), so you can't alias it, not in the `import`/`require` anyway – Liam Feb 23 '18 at 16:58

4 Answers4

255

Sure, just use the object destructuring syntax:

 const { old_name: new_name, foo: f, bar: b } = require('module');
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • 16
    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. – technogeek1995 Apr 02 '19 at 16:23
  • 1
    @technogeek1995 you are the real MVP. logged in to SO to thank you! – Nahum Feb 04 '20 at 15:20
  • 3
    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');` – Beau Nov 24 '20 at 00:37
  • In case, its module.exports = () => {some function} then you can assign any variable name you want. const anything = require('module'); – Muhammad Mubashirullah Durrani Aug 30 '23 at 06:34
15

It is possible (tested with Node 8.9.4):

const {foo: f, bar: b} = require('module');
console.log(`${f} ${b}`); // foo bar
barnski
  • 1,642
  • 14
  • 18
4

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

clusterBuddy
  • 1,523
  • 12
  • 39
  • 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);` – tugrul Feb 24 '22 at 12:58
-5

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

const m = require('module');
const f = m.foo;
const b = m.bar;
Rafael Paulino
  • 570
  • 2
  • 9