简体   繁体   English

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

[英]How to get a variable from a file to another file in Node.js

Here is my first file:这是我的第一个文件:

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

I want this configuration variable in another file, so I have done this in another file:我想在另一个文件中使用这个配置变量,所以我在另一个文件中做了这个:

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

But it gives me an error.但它给了我一个错误。

TypeError: Cannot read property 'confvar' of undefined类型错误:无法读取未定义的属性“confvar”

What can I do?我能做什么?

You need module.exports :你需要module.exports

Exports出口

An object which is shared between all instances of the current module and made accessible through require().在当前模块的所有实例之间共享并通过 require() 访问的对象。 exports is the same as the module.exports object. export 与 module.exports 对象相同。 See src/node.js for more information.有关更多信息,请参阅 src/node.js。 exports isn't actually a global but rather local to each module. export 实际上不是全局的,而是每个模块的局部变量。

For example, if you would like to expose variableName with value "variableValue" on sourceFile.js then you can either set the entire exports as such:例如,如果您想在sourceFile.js上使用值为"variableValue" variableName公开,那么您可以将整个导出设置为:

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

Or you can set the individual value with:或者您可以使用以下方法设置单个值:

module.exports.variableName = "variableValue";

To consume that value in another file, you need to require(...) it first (with relative pathing):要在另一个文件中使用该值,您需要先require(...)它(使用相对路径):

const sourceFile = require('./sourceFile');
console.log(sourceFile.variableName);

Alternatively, you can deconstruct it.或者,您可以解构它。

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

If all you want out of the file is variableName then如果你想要的文件是variableName那么

./sourceFile.js: ./sourceFile.js:

const variableName = 'variableValue'
module.exports = variableName

./consumer.js: ./consumer.js:

const variableName = require('./sourceFile')

Edit (2020):编辑(2020):

Since Node.js version 8.9.0 , you can also use ECMAScript Modules with varying levels of support.Node.js 版本 8.9.0 开始,您还可以使用具有不同支持级别的 ECMAScript 模块。 The documentation .文档

  • For Node v13.9.0 and beyond, experimental modules are enabled by default对于 Node v13.9.0 及更高版本,默认启用实验模块
  • For versions of Node less than version 13.9.0, use --experimental-modules对于低于 13.9.0 的 Node 版本,使用--experimental-modules

Node.js will treat the following as ES modules when passed to node as the initial input, or when referenced by import statements within ES module code:当作为初始输入传递给 node 时,或者当 ES 模块代码中的 import 语句引用时,Node.js 会将以下内容视为 ES 模块:

  • Files ending in .mjs ..mjs结尾的.mjs
  • Files ending in .js when the nearest parent package.json file contains a top-level field "type" with a value of "module" .当最近的父package.json文件包含值为"module"的顶级字段"type"时,以.js结尾的文件。
  • Strings passed in as an argument to --eval or --print , or piped to node via STDIN, with the flag --input-type=module .字符串作为参数--eval--print ,或通过 STDIN 管道传输到节点,带有标志--input-type=module

Once you have it setup, you can use import and export .设置完成后,您可以使用importexport

Using the example above, there are two approaches you can take使用上面的示例,您可以采用两种方法

./sourceFile.js: ./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: ./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: ./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 ./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

File FileOne.js :文件FileOne.js

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

File FileTwo.js :文件FileTwo.js

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

This example works best for React.这个例子最适合 React。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM