tsconfig-paths icon indicating copy to clipboard operation
tsconfig-paths copied to clipboard

Class is loaded twice on different pathes

Open cluxig opened this issue 2 years ago • 4 comments

Imagine you have a class X:

import { SimpleService } from '@/services/simple-service.ts';
import { injectable } from 'tsyringe';

@injectable()
export class X {
    constructor(s: SimpleService) {}
}

and a class Y:

import { SimpleService } from '../services/simple-service.ts';
import { injectable } from 'tsyringe';

@injectable()
export class Y {
    constructor(s: SimpleService) {}
}
import { singleton } from 'tsyringe';

@singleton()
export class SimpleService {
    constructor() {}
}

tsconfig.json

{
 ...
 "paths": { "@/*": [ "src/*" ] }
}

Than X and Y load their own class SimpleService. This is problematic, if you use dependency injection, i.e. with tsyringe (@singleton()), or other Constructor-related Type token things, because now the Type class SimpleService just exists two times at runtime. I think it's not related to tsyringe, because the registration-key is just the class-Type. Other frameworks will fail similarly.

If you either always use the relative imports or always the absolute imports, just one loaded class exists at runtime.

Hence tsconfig-paths is probably doing something wrong. Both imports must lead to same loaded class at runtime.

cluxig avatar Dec 14 '22 15:12 cluxig

I have same issue. I am using absolute import in one place and relative import in another place for class and instanceof is failing because of that:

// httpError.ts
export class HttpError extends Error {...};

// foo.ts
import { HttpError } from '@errors'; // absolute import

export const foo = () => {
  throw new HttpError(...);
}

// index.ts
import { HttpError } from './errors'; // relative import

try {
  foo();
} catch(error){
  console.log(error instanceof HttpError); // false
}

nemmtor avatar Dec 18 '22 19:12 nemmtor

Probably duplicate of this one

nemmtor avatar Dec 18 '22 19:12 nemmtor

Confirm, that is a critical issue for library. Cannot rely on instances anymore.

Having non-unique singleton is critical.

overshom avatar Dec 18 '23 18:12 overshom

This solution helped me to fix my app for tsconfig-paths issue https://github.com/nestjs/nest/issues/986#issuecomment-509295864

overshom avatar Dec 18 '23 18:12 overshom