Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
9
rated 0 times [  13] [ 4]  / answers: 1 / hits: 57877  / 6 Years ago, fri, february 23, 2018, 12:00:00

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?


More From » node.js

 Answers
8

Sure, just use the object destructuring syntax:


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

[#55078] Tuesday, February 20, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
blaisep

Total Points: 748
Total Questions: 95
Total Answers: 108

Location: Federated States of Micronesia
Member since Sun, May 16, 2021
3 Years ago
blaisep questions
Wed, Dec 16, 20, 00:00, 4 Years ago
Sun, Aug 16, 20, 00:00, 4 Years ago
Tue, Nov 12, 19, 00:00, 5 Years ago
Mon, Nov 11, 19, 00:00, 5 Years ago
;