简体   繁体   中英

How do you fix this circular dependency issue in node

` I'm getting errors such as Type variable is undefined and getLastUnknownAlbumTrackNumber is not a function

I installed madge to check circular dependencies but I dont know how to resolve them

following is the output from madge

const madge = require('madge');

madge('./server.js').then((res) => {
    console.log(res.circular());
});

OUTPUT:
(node:6960) Warning: Accessing non-existent property 'getLastUnknownAlbumTrackNumber' of module exports inside circular dependency
(node:6960) Warning: Accessing non-existent property 'Type' of module exports inside circular dependency
[
[ 'jobs/index.js', 'models/index.js' ],
[ 'models/index.js', 'services/metadata.js' ]
]

The following are the related imports & exports

jobs/index.js

const { getMovieMetaData, getTVShowMetaData, getAlbumMetaData } = require('../models');
...
module.exports = { getAll, upsertAll, getLastUnknownAlbumTrackNumber }

services/metadata.js

const { Type } = require('../models');
...
module.exports = Metadata

models/index.js

const { getLastUnknownAlbumTrackNumber } = require('../jobs');
const metadataServiceConstructor = require('../services/metadata');
const metadataService = new metadataServiceConstructor()
...
module.exports = { Type, getMovieMetaData, getTVShowMetaData, getAlbumMetaData }

What do you expect to happen? An attempt to resolve a circular import would result in infinite recursion.

Even if you're using this tool to check for circular imports, it's not static analysis, so the code still needs to be run, hence you encounter the same issue.

As a side note, why are you using this tool at all? It's clear where the circular import lies. You need to refactor to avoid this.

At first read, this answer may seem a bit cryptic
This is due to nature of cyclic dependency .

Once you understand it, it will be easy to fix your solution too

Issue:

1.js -> 2.js -> 3.js
                3.js -> 4.js -> 2.js ( `cycle` )

Solution that worked:

1.js -> 2.js `(remove connection)`
               3.js -> 4.js -> 2.js
1.js -> `200.js (add new)` -> 3.JS

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