在Node.js中如何从一个文件获取变量并传递到另一个文件?

84

这是我的第一个文件:

var self = this;
var config = {
    'confvar': 'configval'
};

我想把这个配置变量放在另一个文件中,因此我在另一个文件中做了如下操作:

conf = require('./conf');
url = conf.config.confvar;

但是它给我一个错误。

TypeError: 无法读取未定义的属性 'confvar'

我该怎么办?


这个回答解决了你的问题吗?在Node.js中如何在文件之间共享变量? - UrbanConor
2个回答

174

编辑(2020年):

自从Node.js版本8.9.0以来,你也可以使用ECMAScript模块,并具有不同程度的支持。 文档

  • 对于Node v13.9.0及以上版本,默认启用实验性模块
  • 对于Node版本低于13.9.0的版本,请使用--experimental-modules

当以下内容作为初始输入传递给node,或作为ES模块代码中的导入语句引用时,Node.js将把以下内容视为ES模块:

  • .mjs结尾的文件。
  • .js结尾且其最近的package.json父级包含顶级字段"type",其值为"module"的文件。
  • 作为参数传递给--eval--print的字符串,或通过STDIN管道传递给node,标志为--input-type=module

一旦设置完成,您就可以使用importexport了。

使用上面的示例,您可以采取两种方法

./sourceFile.js:

// This is a named export of variableName
export const variableName = 'variableValue'
// Alternatively, you could have exported it as a default. 
// For sake of explanation, I'm wrapping the variable in an object
// but it is not necessary. 
// You can actually omit declaring what variableName is here. 
// { variableName } is equivalent to { variableName: variableName } in this case. 
export default { variableName: variableName } 

./consumer.js:

// There are three ways of importing. 
// If you need access to a non-default export, then 
// you use { nameOfExportedVariable } 
import { variableName } from './sourceFile'
console.log(variableName) // 'variableValue'

// Otherwise, you simply provide a local variable name 
// for what was exported as default.
import sourceFile from './sourceFile'
console.log(sourceFile.variableName) // 'variableValue'

./sourceFileWithoutDefault.js:

// The third way of importing is for situations where there
// isn't a default export but you want to warehouse everything
// under a single variable. Say you have:
export const a = 'A'
export const b = 'B'

./consumer2.js

// Then you can import all exports under a single variable
// with the usage of * as:
import * as sourceFileWithoutDefault from './sourceFileWithoutDefault'

console.log(sourceFileWithoutDefault.a) // 'A'
console.log(sourceFileWithoutDefault.b) // 'B'

// You can use this approach even if there is a default export:
import * as sourceFile from './sourceFile'

// Default exports are under the variable default:
console.log(sourceFile.default) // { variableName: 'variableValue' }

// As well as named exports:
console.log(sourceFile.variableName) // 'variableValue

您可以重新导出另一个文件中的任何内容。当您在一个目录中有一个单一的出口点(index.{ts|js}),但有多个文件时,这非常有用。

假设您有以下文件夹结构:

./src
├── component
│   ├── index.js
│   ├── myComponent.js
│   └── state.js
└── index.js

您可能从store.js和my-component.js中有各种不同的导出,但只想导出其中一些。

./src/component/myComponent.js:

import createState from "./state";
export function example(){ };

./src/component/state.js:

export default function() {}

./src/component/index.js

export { example as default } from "./myComponent";
export * from "./myComponent"

./src/index.js

export * from "./component"

Translated Answer:

要实现模块的公共访问,需要使用module.exports

模块导出对象

该对象在当前模块中是共享的,可通过 require() 访问。exports 对象和 module.exports 对象是同一个对象。更多信息请查看 src/node.js 。exports 对象并不是全局变量,而是每个模块本地的。

例如,如果你想要在 sourceFile.js 中将 variableName 的值设置为 "variableValue",则可以按以下两种方式之一设置整个 exports 对象:

module.exports = { variableName: "variableValue" };

或者您可以使用以下方式设置单个值:

module.exports.variableName = "variableValue";

为了在另一个文件中使用该值,你需要先使用相对路径的 require(...) 将其引入:
const sourceFile = require('./sourceFile');
console.log(sourceFile.variableName);

或者,您可以对其进行分解。

const { variableName } = require('./sourceFile');
//            current directory --^
// ../     would be one directory down
// ../../  is two directories down

如果你只想从文件中获取variableName,那么

./sourceFile.js:

const variableName = 'variableValue'
module.exports = variableName

./consumer.js:

const variableName = require('./sourceFile')

1
你能在不需要它的情况下调用变量吗?如果有很多文件必须包含相同的变量或模块,会发生什么?我是否必须为所有文件使用 require?在主文件中是否有全局声明,以便我们可以在所有其他文件中使用它们? - Ivan Juarez
1
你能在使用的文件中使用 import 吗? - user1063287
1
我在文档中注意到他们使用 exports.variableName = "variableValue"; 而不是 module.exports.variableName = "variableValue";。哪一种方式更好?为什么有两种方法呢? - Tomiwa
1
@Tomiwa https://dev59.com/c2Qo5IYBdhLWcg3wBLjy#16383925 - Chance

11

文件 FileOne.js:

module.exports = { ClientIDUnsplash : 'SuperSecretKey' };

文件 FileTwo.js:

var { ClientIDUnsplash } = require('./FileOne');

这个示例最适合React。


这对我没用(FileTwo.js中未定义ClientIDUnsplash)。取而代之的是这个:const ClientIDUnsplash = require('./FileOne'); - jstm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接