您需要的是module.exports
出口产品
在当前模块的所有实例之间共享并可以通过require()访问的对象。export与module.exports对象相同。有关更多信息,请参见src /
node.js。导出实际上不是全局的,而是每个模块的本地性。
例如,如果您想公开
variableName使用价值
"variablevalue",
sourceFile.js则可以这样设置整个出口:
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 2 directories down如果你想出来的文件
variableName,然后
./sourceFile.js:
const variableName = 'variablevalue'module.exports = variableName
./consumer.js:
const variableName = require('./sourceFile')编辑(2020年):
从开始
Node.js version8.9.0,您还可以使用具有不同支持级别的ECMAscript模块。该文档
- 对于Node v13.9.0及更高版本,默认情况下启用实验模块
- 对于低于版本13.9.0的Node版本,请使用
--experimental-modules
当传递给节点作为初始输入或被ES模块代码中的import语句引用时,Node.js将把以下内容视为ES模块:
- 以结尾的文件
.mjs。 .js在最近的父package.json文件包含"type"值为的顶级字段时结束的文件"module"。- 带有标志的字符串作为参数通过STDIN 传递到
--evalor--input-type=module。
设置完成后,您可以使用
import和
export。
使用上面的示例,您可以采用两种方法
./sourceFile.js:
// this is a named export of variableNameexport 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


