简体   繁体   中英

Node: 'Best Practice' of js files using other js files

Here is the scenario:

Main.js:

var one = require(./one.js);
var two = require(./two.js);

two.foo();

one.js:

module.exports = {
  foo: function () {
    console.log("this was called by two");
  }
};

two.js:

module.exports = {
  foo: function () {
    one.foo();
  }
};

I'm calling one of two's functions in main which then calls one's function, which then logs. Currently, I get an error in two.js saying "one is not defined." The goal of this was to break up a giant js file into smaller ones that all use each other in some way. If this is not possible please let me know.

So far the only fixes I can think of are:

  1. requiring one.js in two.js
  2. passing an instance of one into two in some form of init function
  3. some global instance of one?

You need to require one.js in two.js, like you said. Every file that accesses another file needs to require that file.

Like this:

Main.js:

var two = require(./two);
two.foo();

one.js:

module.exports = {
  foo: function () {
    console.log("this was called by two");
  }
};

two.js:

var one = require(./one);
module.exports = {
  foo: function () {
    one.foo();
  }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM