0

I am trying to write a very simple Typescript project but it does not seems to work. Here's my project structure

(including also the dist folder):

├── dist
│   ├── hello.js
│   └── index.js
├── package-lock.json
├── package.json
├── src
│   ├── hello.ts
│   └── index.ts
└── tsconfig.json

my hello.ts:

export function sayHello() {
  console.log("Hello");
}

my index.ts:

import { sayHello } from "./hello";

sayHello();

my tsconfig.json:

{
  "compilerOptions": {
    "rootDirs": ["src"],
    "outDir": "dist",
    "lib": ["es2020"],
    "target": "es2020",
    "module": "esnext",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "types": ["node"]
  }
}

my package.json:

{
  "name": "ts-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "compile": "tsc",
    "start": "npm run compile && node ./dist/index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "type": "module",
  "devDependencies": {
    "@types/node": "^20.4.9",
    "typescript": "^5.1.6"
  }
}

The error I am getting is:

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '****/ts-test/dist/hello' imported from ****/ts-test/dist/index.js

What am I missing?

Arty
  • 859
  • 2
  • 12
  • 31
Essay97
  • 648
  • 1
  • 9
  • 24

3 Answers3

0

TRY Update your tsconfig.json to include:

{
  "compilerOptions": {
    "rootDir": "src",
    "outDir": "dist",
    // ...
  }
}
0

Try change your import like this:

import { sayHello } "./hello.js";
Arty
  • 859
  • 2
  • 12
  • 31
0

From rootDir definition:

Importantly, rootDir does not affect which files become part of the compilation. It has no interaction with the include, exclude, or files tsconfig.json settings.

Most likely you also need "include": ["src/**/*"] to tell typescript to include all files in src in the compilation (include documentation).

Hoopra
  • 201
  • 2
  • 7