在Javascript / node.js中共享模块之间的变量?
16lz
2021-01-22
I have 3 node files:
我有3个节点文件:
// run.js
require('./configurations/modules');
require('./configurations/application');
// modules.js
var express = module.exports.express = require('express');
var app = module.exports.app = express.createServer();
// app.js
app.configure(...)
Run.js requires both files, modules.js which require a module and creates a variable, and app.js which should use that variable. But I get an error on app.js cause app isn't defined.
Run.js需要两个文件,modules.js需要一个模块并创建一个变量,app.js应该使用该变量。但我在app.js上收到错误导致app未定义。
Is there a way to make this possible?
有没有办法让这成为可能?
2 个解决方案
#1
8
Everything declared in a module is local to that module unless it is exported.
除非导出模块,否则模块中声明的所有内容都是该模块的本地模块。
Exported objects from one module can be accessed from other modules that reference it.
可以从引用它的其他模块访问一个模块中的导出对象。
$ cat run.js
require('./configurations/modules');
require('./configurations/application');
$ cat configurations/modules.js
exports.somevariable = {
someproperty: 'first property'
};
$ cat configurations/application.js
var modules = require('./modules');
modules.somevariable.something = 'second property';
console.log(modules.somevariable);
$ node run.js
{ someproperty: 'first property',
something: 'second property' }
更多相关文章
- javascript变量:全局?还是局部?这个得注意
- Python 3.4:试图让这个模块对这个2d数组中的销售总数求和。不工作
- windows下安装python的三方模块pyExcelerator的问题
- Python安装模块(numpy等)问题的两种解决办法——常规方法和Anacond
- Python中psutil模块的安装
- 求助:Python是否可以用一行代码来同时给变量赋值并打印变量的值
- Python常用模块-摘要算法(hashlib)
- Python学习系列(六)(模块)
- Python基础(4) - 变量