[英]Can I use alias with NodeJS require function?
I have an ES6 module that exports two constants:我有一个导出两个常量的 ES6 模块:
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:当我使用 NodeJS 模块时,我会这样写:
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?现在当我在另一个模块中使用它时,我可以像使用 ES6 模块一样重命名导入的变量吗?
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?如何在 NodeJS 模块中重命名导入的常量?
当然,只需使用对象解构语法:
const { old_name: new_name, foo: f, bar: b } = require('module');
It is possible (tested with Node 8.9.4):这是可能的(使用 Node 8.9.4 测试):
const {foo: f, bar: b} = require('module');
console.log(`${f} ${b}`); // foo bar
Yes, a simple destructure would adhere to your request.是的,一个简单的解构将符合您的要求。
var events = require('events');
var emitter = new events.EventEmitter();
const emitter = {EventEmitter} = require('events');
emitter()
will alias the method EventEmitter()
emitter()
将别名方法EventEmitter()
Just remember to instantiate your named function: var e = new emitter();
请记住实例化您的命名函数:
var e = new emitter();
😁 😁
I would say it is not possible, but an alternative would be:我会说这是不可能的,但另一种选择是:
const m = require('module');
const f = m.foo;
const b = m.bar;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.