Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't import from absolute paths using Typescript and NodeJS

I've tried many things to solve this issue. I'm trying to import from absolute paths defined on my tsconfig.json

on a file on my project I'm trying to use import { UserModel } from "model/User";

And on my tsconfig.json I have

{
....
"baseUrl": "src", 
"paths": {
  "model/*": ["model/*"]`
  }
....
}

I've tried changing the baseUrl to ".", "./" and changing the paths as well, but I'm always getting the same error:

Error: Cannot find module 'model/User'

I have also tried to add an index.ts file to the model folder and export models from there, but still.. same issue. Any help is appreciated.

like image 333
Lheonair Avatar asked Nov 18 '25 05:11

Lheonair


1 Answers

If you are writing a package, then probably you are reserved to using the ttypescript lib + @zerollup/ts-transform-paths plugin - those will do the job. Also, building your package will have to use ttsc instead of tsc.

If, on the other hand, you are using a bundler to bundle your code together (like webpack), you will have to reserve to the ways provided by the bunder's config.

Also, if you are using ESLint, you'll have to make sure it uses tsconfig.json via eslint-import-resolver-typescript npm package.

Also, if you are using Jest for unit-tests, you will have to enumerate the possible "roots" like this:

  moduleDirectories: ['node_modules', 'src'],
like image 119
Kostiantyn Ko Avatar answered Nov 19 '25 20:11

Kostiantyn Ko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!