2

I'm currently searching since hours how to import local ES6 modules with an absolute path.

Whenever I try to import something in a module like :

import { Module } from "src/my-module";

I get an error "Error: Cannot find module 'src/my-module'. Here is my tsconfig :

{
"compilerOptions": {
"lib": \["ES6"\],
"target": "ES6",
"baseUrl": "./",
"rootDir": "src",
"esModuleInterop": true,
"moduleResolution": "node",
}
"include": \["src/\*\*/\*.ts"\],
"exclude": \["node_modules"\]
}

I tried to fill the paths attribute of compilerOptions in tsconfig, modifying baseUrl, installing typescript-transform-paths, ilearnio/module-alias ... I'm using ts-node

5
  • Absolute path is path starting from disk letter, I assume you don't want to do it. What is your goal? Commented Nov 8, 2022 at 23:42
  • Your error Cannot find module 'src/my-module is self-explanatory - it means your module is not inside the folder you are trying to import it from. Make sure you are importing it from the correct directory. Commented Nov 8, 2022 at 23:53
  • @Lonli-Lokli Relative to the project's main folder Commented Nov 8, 2022 at 23:58
  • @Aleksandar Visual studio is higlighting it and isn't detecting any problem, the file exists in the specified folder but when I run tsnode, it tells that the module doesn't exist Commented Nov 8, 2022 at 23:58
  • @Aleksandar import { Module } = require("src/my-module"); isn't a valid operation, we can't assign require to an import definition Commented Nov 9, 2022 at 0:18

1 Answer 1

2

I had to install tsconfig-paths

npm i -D tsconfig-paths

And update my tsconfig.json with the "ts-node" block:

{
  "ts-node": {
    "require": ["tsconfig-paths/register"]
  },

  "compilerOptions" {
    // ....
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

could you cleanup your answer's formatting a bit? I'm not clear on what the solution is.
@Slbox Done sorry :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.