Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I'm getting Error [ERR_MODULE_NOT_FOUND]: Cannot find module when running the server

I'm doing a startup server. Basically It has initial setup with express and nodemon dependencies. Unfortunately, I'm getting ERR_MODULE_NOT_FOUND when running yarn dev or npm run dev Here is the code and file structure I have. enter image description here

like image 496
Raymond Avatar asked Jul 13 '26 02:07

Raymond


2 Answers

The issue is a missing file extension. The import needs to look like this:

import { sampleExport } from "../config/env.js";
//                                         ^^^

import doesn't use the same algorithm that require used. Instead, it works according to the ECMAScript Modules specification, which requires a definite extension.

This is also explained in the node.js docs for ECMAScript modules:

A file extension must be provided when using the import keyword to resolve relative or absolute specifiers. Directory indexes (e.g. './startup/index.js') must also be fully specified.

This behavior matches how import behaves in browser environments, assuming a typically configured server.

like image 117
CherryDT Avatar answered Jul 15 '26 15:07

CherryDT


You need to add .js extension index.js:

import { SampleExport } from "../path/file.js"

In my opinion, it is better to use .env files together with some npm package or even a json file.

like image 38
Jorge Montejo Avatar answered Jul 15 '26 17:07

Jorge Montejo



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!