Can I use alias with NodeJS require function?

前端 未结 4 1333
春和景丽
春和景丽 2020-12-28 11:49

I have an ES6 module that exports two constants:

export const foo = \"foo\";
export const bar = \"bar\";

I can do the following in another

相关标签:
4条回答
  • 2020-12-28 12:27

    It is possible (tested with Node 8.9.4):

    const {foo: f, bar: b} = require('module');
    console.log(`${f} ${b}`); // foo bar
    
    0 讨论(0)
  • 2020-12-28 12:41

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

    const m = require('module');
    const f = m.foo;
    const b = m.bar;
    
    0 讨论(0)
  • 2020-12-28 12:43

    Sure, just use the object destructuring syntax:

     const { old_name: new_name, foo: f, bar: b } = require('module');
    
    0 讨论(0)
  • 2020-12-28 12:44

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

    0 讨论(0)
提交回复
热议问题