0

I have a TypeScript file called server.ts, I run npx tsc to transpile the JavaScript. To start it, I then run node dist/server.js. This works.

If I add a file db/mongodb-client.ts and add an import to server.ts like this:

import db from "./db/mongodb-client";

and build again (npx tsc) I get two JavaScript files (dist/server.js and dist/db/mongodb-client.js). When starting (node dist/server.js) I get the following error:

Cannot find module 'dist\db\mongodb-client' imported from dist\server.

If I change the import to:

import db from "./db/mongodb-client.js";

it works. But that looks strange to me, since the source file is TypeScript. Do I need to configure something to get this working? Or build/start differently? Or am I expecting something wrong?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Nausika
  • 495
  • 7
  • 13
  • That's just how ES module resolution works by default. Yes you're writing .ts files but (as your opening paragraph states) they're transpiled to .js - that's what's failing to resolve at runtime. – jonrsharpe Aug 21 '23 at 16:54
  • Possible duplicate? https://stackoverflow.com/questions/62619058/appending-js-extension-on-relative-import-statements-during-typescript-compilat – Jared Smith Aug 21 '23 at 17:04

0 Answers0