TypeScript file resolved by webpack alias in different directory structure to node_modules can't find them

Viewed 21

Sorry for vague title, hard to summarise without making it too convoluted. My project structure is as below, simplified for ease of understanding.

  • packages
    • _shared
      • index.ts
    • myProject
      • backend
        • node_modules/*
        • index.ts
        • package.json
      • frontend
        • node_modules/*
        • index.ts
        • package.json
    • secondProjectEtc...
      • backend
        • ...
      • frontend
        • ...

Each project's backend and frontend has their own node_modules and are not within workspaces, this must stay this way for reasons it's not worth going into. In each project's backend and frontend I have a webpack alias (also paths set up in the tsconfig) referencing the _shared folder, which contains only shared code, no package.json or node_modules. This is because each project has the potential to have different versions of libraries, and I don't want to bog down each bundle with multiple versions of modules.

As an example of my issue, in packages/_shared/index.ts I have this class below

import axios from 'axios';

export class Point {

    x: number;
    y: number;
    fakeMethod: () => Promise<any>;

    constructor(x = 0, y = 0) {
        this.x = x;
        this.y = y;
        this.fakeMethod = () => axios.post('fakeUrl');
    }
}

...which I then import in packages/myProject/backend/index.ts. In myProject/backend I have axios installed, but when I run the webpack build I get the following error.

ERROR in .../packages/_shared/index.ts              
  Module not found: Error: Can't resolve 'axios' in '.../packages/_shared/index.ts'
   @ .../packages/_shared/index.ts 1:0-26 6:32-37
   @ ./index.ts

Webpack appears to be trying to resolve the library in the _shared folder but I was expecting it to be resolving the node_modules in the corresponding project. Is there a way to tell the shared project to resolve in the project it's being used in, is there some config I'm missing?

Please ask for any extra clarifications or config you may need, I've tried to keep the issue as simple as possible but may have left out key details.

0 Answers
Related