[英]Import module in node js
I have a object created in src/some/file.js
我在
src/some/file.js
创建了一个对象
module.exports = export_obj
Now i want to access this object from another file src/other/file2.js I tried doing require('export_obj')
but it gives error:Error: Cannot find module现在我想从另一个文件 src/other/file2.js 访问这个对象我尝试做
require('export_obj')
但它给出了错误:错误:找不到模块
The variable name you use inside the module before you copy its value to exports
is irrelevant (and impossible to determine before the file is loaded anyway).在将其值复制到
exports
之前,您在模块中使用的变量名称是无关紧要的(并且无论如何都无法在加载文件之前确定)。
You need to use the filename in the require
statement.您需要在
require
语句中使用文件名。
require('../other/file2.js')
You need to require with relative path.您需要使用相对路径。
other = require('../other/file2');
Without relative path, nodeJS will try to find the package inside node_modules (locally and globally).如果没有相对路径,nodeJS 将尝试在 node_modules 中(本地和全局)查找包。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.