Search code examples
javascriptnpm

Same class instances over different projects


I'm having issues with instances of the same package over different JavaScript projects and I'd like to know if there is any workaround other than modifying the original package. My project setup is the following:

Project A In this project there are several classes that are used on other places. This project is uploaded as a package to the npm repository.

Project B This project has Project A as dependency (via npm) and creates instance generators of the classes provided there. It's kind of a repository of functions that create Project A instances.

Project C This project has Project A as dependency (via npm) as well. The project attempts to generate the instances from Project B and check if there are valid Project A instances.


The problem comes when Project C attempts to check the instanceof from Project B generated instances, because it always returns false. Instances are being created by importing from a project to the other with a require(filepath) the generator function and then executing it.

Maybe it's easier to understand with an example:

Project A

class A {
   // ...
}

Project B

import { A } from 'npm-package-name';

export const generator = () => new A(); 

Project C

import { A } from 'npm-package-name';

const { generator } = require('...');
const a = generator();

return a instanceof A; // false

I tried to upload Project A as an npm package because I thought that way the definitions would be somehow shared between projects but clearly it didn't work.


Solution

  • I've managed to solve the issue I was having by configuring the environment where the projects run in a specific way. What I needed was to share the same Project A dependency between different projects, and npm could not provide that functionality as every project has its own node_modules folder. However, pnpm allows developers to work with workspaces where the same dependencies are shared over projects. This improves memory space, but it also makes the instanceof problem go away as the class definitions are the same.

    This may not be the best solution for every person having issues with this, but in my case the projects and their behavior could not be changed, so coming across some way to make it work that is external to the projects' code was what I needed.