如何在NodeJS中的javascript中一次导入多个变量?

时间:2016-01-08 18:08:20

标签: javascript node.js

假设我有一个javascript模块first_file.js

var first = "first",
    second = "second",
    third = "third";

module.exports = {first, second, third};

如何将这些文件导入一行中的另一个文件?以下仅导入third

var first, second, third = require('./path/to/first_file.js');

3 个答案:

答案 0 :(得分:12)

您正在导出具有这些属性的对象。你可以直接使用这个对象来获取它们:

var obj = require('./path/to/first_file.js');
obj.first;
obj.second;
obj.third;

或使用解构:

var { first, second, third } = require('./path/to/first_file.js');

从版本4.1.1开始,Node.js尚不支持开箱即用的解构。

答案 1 :(得分:5)

在ES6(ECMAScript 2015)中,您可以使用对象解构:

const { first, second, third } = require('./path/to/first_file.js');

答案 2 :(得分:1)

您可以将它们存储在数组中:

module.exports = [first, second, third];
相关问题