Can I use alias with NodeJS require function?

xMort picture xMort · Feb 23, 2018 · Viewed 27.7k times · Source

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?

Answer

Jonas Wilms picture Jonas Wilms · Feb 23, 2018

Sure, just use the object destructuring syntax:

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