我可以使用别名与 NodeJS 需要的功能?

我有一个导出两个常量的 ES6模块:

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

我可以在另一个模块中执行以下操作:

import { foo as f, bar as b } from 'module';
console.log(`${f} ${b}`); // foo bar

当我使用 NodeJS 模块时,我会这样写:

module.exports.foo = "foo";
module.exports.bar = "bar";

现在,当我在另一个模块中使用它时,我是否可以以某种方式将导入的变量重命名为 ES6模块?

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

如何重命名 NodeJS 模块中导入的常量?

52506 次浏览

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

const m = require('module');
const f = m.foo;
const b = m.bar;

It is possible (tested with Node 8.9.4):

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

Sure, just use the object destructuring syntax:

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

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