我可以在NodeJS require函数中使用别名吗? [英] Can I use alias with NodeJS require function?
本文介绍了我可以在NodeJS require函数中使用别名吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个导出两个常量的ES6模块:
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
当我使用NodeJS模块时,我会这样写:
When I use NodeJS modules, I would have written it like this:
module.exports.foo = "foo";
module.exports.bar = "bar";
现在当我在另一个模块中使用它时,我可以用ES6模块重命名导入的变量吗? / p>
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
如何在NodeJS模块中重命名导入的常量?
How can I rename the imported constants in NodeJS modules?
推荐答案
当然,只需使用对象解构语法:
Sure, just use the object destructuring syntax:
const { foo: f, bar: b } = require('module');
这篇关于我可以在NodeJS require函数中使用别名吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文