typescripttypescript-module-resolution

Issue with typescript path resolution. (Error: Cannot find module '[module_name]')


I have a node project setup with typescript. Everything worked perfectly fine, but lately I've been wanting to implement path resolution. Why is it such a hassle?

Here is my project architecture:

└───src
    ├───models
    ├──────Person.ts
    ├───query
    ├──────index.ts
    └───index.ts
├───package.json
└───tsconfig.json

My tsconfig is setup like so:

{
  "compilerOptions": {
    "moduleResolution": "node",
    "rootDir": "./src",
    "outDir": "./build",
    "baseUrl": "./src",
    "paths": {
      "@models/*": [ "models/*" ]
    }
  },
  "exclude": [ "node_modules", "build" ],
  "include": [ "src/**/*.ts" ],
}

Everything works perfectly fine within VS-code.
I can easily import Person.ts from my index file using:

import Person from '@models/Person'.

tsc builds without any errors or warnings.

But when I run

node build/index.js

It gives me the following error:

Error: Cannot find module '@models/Person'

It seems like paths are not correctly converted after typescript compilation.

Any idea?


Solution

  • Here is the solution I finally went for:
    I've added cross-env and tsconfig-path to my package.json.
    Allowing me to run my project like this:

    "scripts": {
      "start": "cross-env TS_NODE_BASEURL=./build node --require tsconfig-paths/register ./build/index.js",
      "build": "tsc",
      "watch": "tsc-watch --onSuccess \"yarn start\""
    },
    

    Note here that I'm using the cross-env package only because I'm on windows.

    I still don't understand why path resolving isn't native to typescript compilation but anyways. It works like a charm! and on both Linux&Windows