'How to debug nodejs app that is importing a library twice?

I'm using a library called yjs that needs to be imported just once, across all dependencies. Currently, when I run my app, I get the following warning message from yjs:

Yjs was already imported. Importing different versions of Yjs often leads to issues.

How can I see what is importing this library, and where the double-import might be coming from?

When I run pnpm why yjs it tells me a little info:

$ pnpm why yjs
Legend: production dependency, optional only, dev only

[email protected] /home/duane/Relm/relm/server

dependencies:
y-websocket 1.3.18-canadaduane
├─┬ y-leveldb 0.1.1
│ └── yjs 13.5.27 peer
└── yjs 13.5.27 peer
yjs 13.5.27

But it isn't showing me some of the places that I know are also importing yjs. For example, this project has several pnpm workspaces, and other workspaces that use yjs are dependencies of this one--but they aren't visible in the pnpm why report.

Is there a way to "print" a log of import statements as the app runs, and show what js files are importing what packages/files?



Solution 1:[1]

In nodejs 18 (and I think nodejs 16), there is an import loader hook mechanism that can be used if set up on the command line (Note: this mechanism is not available to "any old package", as that would be a security concern):

  1. Create a file named es-import-trace.js in your project root (wherever you normally run node):
export const load = async (url, context, defaultLoad) => {
    console.log('import: ' + url);
    return await defaultLoad(url, context);
};
  1. Use node's --loader command-line argument to run your node app with the es-import-trace.js file:
node --loader ./es-import-trace.js dist/server.js
  1. You will get output such as the following, allowing you to see each import:
import: file:///home/duane/Relm/relm/server/dist/server.js
import: node:fs
import: file:///home/duane/Relm/relm/server/dist/config.js
import: file:///home/duane/Relm/relm/server/dist/server_ws.js
import: file:///home/duane/Relm/relm/server/dist/db/db.js
... etc. ...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Duane J