Need help with 'Cannot find module' error

I ran into a problem when deploying my Express app on Render:

Cannot find module '/opt/render/project/src/server/dist/db/connect' imported from /opt/render/project/src/server/dist/server.js

My settings:
Root directory: server
Build command: server/ $ (added automatically) npm install; npm run build && ls dist/db
Start command: server/ $ (added automatically) npm start.

What I’ve tried:

  • added ls dist/db to specifically check the existence of the file in question, and it does exist (see left screenshot);
  • checked the casing of the file names;
  • checked the paths;
    tsconfig.ts:
{
  "compilerOptions": {
    "target": "es2016",
    "moduleResolution": "node",
    "allowJs": true,
    "outDir": "./dist",
    "esModuleInterop": true
    "forceConsistentCasingInFileNames": true,
    "strict": false,
    "skipLibCheck": true
  }
}

package.json:

{
  "main": "server.ts",
  "engines": {
    "node": ">=20.11.1"
  },
  "scripts": {
    "dev": "nodemon server.ts",
    "build": "tsc",
    "start": "node dist/server.js"
  },
  "type": "module",
   (...)

I import the file like this:
server.js:

import connectDB from './db/connect'; 

My file structure inside the root directory is on the right screenshot.

I’d be grateful if someone could help me with my issue.

Hi there,

I believe this is happening because your imports are missing the js extension. There is a fair amount of background as to why it is like this, but this Stack Overflow post has some options on how to resolve it: https://stackoverflow.com/questions/62619058/appending-js-extension-on-relative-import-statements-during-typescript-compilat

You could also remove the "type": "module" line from your package.json and have Typescript output CommonJS modules.

Regards,

Keith
Render Support, UTC+10 :australia:

1 Like

Thanks, Keith, I resolved my issue by installing tsc-alias and including it in my build command as your SO link suggested.
However, removing "type": "module" wasn’t an option as I got Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension. warning in that case.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.