javascript 我可以在 NodeJS 的 require 函数中使用别名吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48952736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:21:02  来源:igfitidea点击:

Can I use alias with NodeJS require function?

javascriptnode.jsecmascript-6commonjs

提问by xMort

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 模块中重命名导入的常量?

回答by Jonas Wilms

Sure, just use the object destructuring syntax:

当然,只需使用对象解构语法:

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

回答by barnski

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

回答by Rafael Paulino

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

我会说这是不可能的,但另一种选择是:

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