Share variables between modules in Javascript/node.js?

前端 未结 2 1952
清歌不尽
清歌不尽 2021-01-12 01:33

I have 3 node files:

// run.js

require(\'./configurations/modules\');
require(\'./configurations/application\');

// modules.js

var express = module.export         


        
相关标签:
2条回答
  • 2021-01-12 02:36

    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' }
    
    0 讨论(0)
  • 2021-01-12 02:38

    It looks like you're defining the variable in modules.js, but trying to reference it in app.js. You'll need to have another require in app.js:

    // app.js
    var application = require('./path/to/modules'),
        app = application.app;
    
    app.configure(...);
    
    0 讨论(0)
提交回复
热议问题