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.
Asked
Active
Viewed 1.0k times
2 Answers
10
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.

CherryDT
- 25,571
- 5
- 49
- 74
-
Thank you.I'm working on react frontend and little knowledge on backend How it differ from react project when importing? I import as usual without file extension. – Raymond Feb 01 '22 at 11:58
-
1React uses Webpack as bundler configured in such a way that it resolves `import`s in a more relaxed fashion. If you'd use the browsers' native ESM implementation, `import` would also require a file extension. – CherryDT Feb 01 '22 at 14:38
2
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.

Jorge Montejo
- 485
- 1
- 6
- 17
-
Thank you, yes, I will use .env but I need env.js for my logic to get prod or dev env. I'm confused why it requires the file extension. I'm currently having react project and importing just the file name at the end. – Raymond Feb 01 '22 at 11:33
-
I am glad that my answer will help you, I would be grateful if you would accept it. – Jorge Montejo Feb 01 '22 at 11:43
-
Adding .js to my import worked for me too. Is there a linter that actually warns for that behaviour? @JorgeMontejo – MalcolmXYZ Dec 07 '22 at 09:34
-
1@MalcolmXYZ I don't know of any extension that would work for you, just keep in mind what CherryDT says, when using import instead of require, you should use the .js extension (unless you are using type script of course). – Jorge Montejo Dec 09 '22 at 08:36