简体   繁体   中英

Node.js: how to resolve a circular dependency

I know this question has been asked multiple times, but my case is specific:

I have three files, a controller.js , router.js and an app.js ,

router.js imports controller.js , app.js imports router.js

I need to import something from app.js to controller.js , how would I do that?

you're probably better off restructuring your code to not need it. Maybe create a third class that uses the other two to accomplish what you need, if you have to use a function in app.js you can do like this:

before requiring you should exports express() and functions

app.js

const express = require("express");
const func = () => {
  console.log("I'm in App");
};
var exportFiles = module.exports = {
  app: express(),
  func: func,
};
var { app } = exportFiles;
const fs = require("fs");
const path = require("path");
const bodyParser = require("body-parser");

app.listen(8080, () => {
  console.log("server port is 8080")
})

contolers.js

const {func} = require('../app');

when you call func() in controller result is:

func() // I'm in App

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