这是我的第一份文件:

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

我想把这个配置变量放在另一个文件中,所以我在另一个文件中这样做了:

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

但这给了我一个错误.

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

我能做什么?

推荐答案

编辑(2020年):

Node.js version 8.9.0开始,您还可以使用具有不同支持级别的ECMAScript模块.The documentation

  • 对于 node v13.9.0及更高版本,实验模块默认启用
  • 对于版本低于13.9.0的 node 版本,请使用--experimental-modules

node .当js在ES中被引用时,将以下语句视为输入:

  • 文件以.mjs结尾.
  • 当最近的父文件package.json包含值为"module"的顶级字段"type"时,文件以.js结尾.
  • 字符串作为参数传入--eval--print,或通过STDIN传输到 node ,带有标志--input-type=module.

一旦设置好,就可以使用importexport.

通过上面的例子,你可以采取两种方法

/源文件.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 } 

/消费者.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'

/withsource默认值.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'

/消费者2.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})但有多个文件时,这很有用.

假设您有以下文件夹 struct :

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

你们可以从这两家store 购买各种出口商品.js和我的组件.但只想导出其中的一部分.

./src/component/myComponent.js:

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

./src/组件/状态.js:

export default function() {}

./src/组件/索引.js

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

/src/index.js

export * from "./component"

原始答案:

你需要module.exports:

出口

在当前模块的所有实例之间共享的对象

例如,如果希望在sourceFile.js上显示值为"variableValue"variableName,则可以将整个导出设置为:

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

Or您可以使用以下选项设置单个值:

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,那么

/源文件.js:

const variableName = 'variableValue'
module.exports = variableName

/消费者.js:

const variableName = require('./sourceFile')

Node.js相关问答推荐

使用Vite和ReactJS时,在哪里设置NODE_OPTIONS?

Mongoose更新在^8.0.3版中,许多似乎不能按预期工作

如何从shell脚本中计算ecmascript模块?

创建查询以展开数组并筛选出具有特定值的元素之后的元素

npm错误;无法解析依赖项:npm ERR!对等webpack@;5.x.x;来自@webpack-cli/serve@2.0.5";

使用 playwright 获取页面中同一 url 的所有响应

为什么 Cors 在 NodeJS 中不起作用

如何在 JavaScript 中显示多维数组中使用的一维数组的变量名?

找不到模块bcryptjs

每个数组值在 mongodb 中查找一个文档

为什么当我使用waitForSelector时 Puppeteer 导致我的测试套件挂起 30 秒,即使我在页面和浏览器上调用关闭?

BrowserRouter 无法渲染组件

在 nodejs 中使用 multer 上传文件返回未定义的 req.file 和空的 req.body

Web3.js 脚本在监听 CreatedPairs 时退出

如果我使用像 express 这样的 node 服务器,是否需要 webpack-dev-server

如何以编程方式检测nodejs中的调试模式?

node 应用程序是否有任何独立的 gui 模块

nodejs v10.3.0 的 gulp 任务问题:src\node_contextify.cc:629: Assertion `args[1]->IsString()' failed

NodeJS 中的 HTTPS 请求

npm install packagename --save-dev 不更新 package.json