ExpressJs is return error `ERR_MODULE_NOT_FOUND` if I import the file without `js` extension
Asked Answered
M

20

58

I build a expressJs app by ES6 and I got the below error:

(node:4132) ExperimentalWarning: The ESM module loader is experimental.
internal/modules/run_main.js:54
    internalBinding('errors').triggerUncaughtException(
                              ^

Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'E:\wamp64\www\myDemos\nodeJs\expressJsExample\config\app' imported from E:\wamp64\www\myDemos\nodeJs\expressJsExample\server.mjs
←[90m    at finalizeResolution (internal/modules/esm/resolve.js:255:11)←[39m
←[90m    at moduleResolve (internal/modules/esm/resolve.js:603:10)←[39m
←[90m    at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:644:13)←[39m
←[90m    at Loader.resolve (internal/modules/esm/loader.js:94:40)←[39m
←[90m    at Loader.getModuleJob (internal/modules/esm/loader.js:240:28)←[39m
←[90m    at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:42:40)←[39m
←[90m    at link (internal/modules/esm/module_job.js:41:36)←[39m {
  code: ←[32m'ERR_MODULE_NOT_FOUND'←[39m
}
[nodemon] app crashed - waiting for file changes before starting...

If I use import app from './config/app.js'; then working but if I use import app from './config/app'; then return the above error.

The below is my code:

package.json

{
  "name": "ExpressJsExample",
  "version": "1.0.0",
  "description": "Express Js Example",
  "main": "server.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon server.js"
  },
  "author": "Mukesh Singh Thakur",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "chalk": "^4.0.0",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "http": "0.0.1-security",
    "http-errors": "^1.7.3",
    "jsonwebtoken": "^8.5.1",
    "nodemon": "^2.0.2",
    "pg": "^8.0.0",
    "request": "^2.88.2",
    "sequelize": "^5.21.6"
  },
  "devDependencies": {
    "sequelize-cli": "^5.5.1"
  }
}

server.js

import http from 'http';
import app from './config/app';

const server = http.Server(app);
server.listen(3000, () => {
       return true;
});

app.js

import express from 'express';
const app = express();

export default app;

The example app is available in https://github.com/msthakur08/express-js-example URL. The example files import with '.js' existence but I want to import file without '.js' existence.

Masturbate answered 18/4, 2020 at 15:27 Comment(3)
I am using ES6.Masturbate
what is your node version ?Sheepshank
any solution? i got same issueAlgin
C
89

You can resolve this by: Just add js as an extension to file

Before:

import std from './route/student'

After:

import std from './route/student.js'
Consistent answered 28/2, 2021 at 21:33 Comment(3)
Order of the arguments actually matter!!!!Holy
Solved it. What does this mean?Dissimulate
Is there a better solution to this? It feels ugly to be forced to include .js extension for every import.Baileybailie
B
52

If someone is still searching, I got this error using node version 15, I was importing the files without the .js file extension, adding that fixed my issue.

Brachium answered 8/6, 2021 at 12:6 Comment(2)
Kind of lame that editors/IDE's auto import without the .js extension. Good to know though. I always thought it did not make a difference.Mordant
SyntaxError: Named export 'Request' not found - ExpressJSOvarian
A
22

You can add this to your package json

"scripts": {
    "start": "nodemon --experimental-modules --es-module-specifier-resolution=node index.js"
},
Aarau answered 3/5, 2021 at 6:35 Comment(7)
Hey, I've added this but nothing helpedCrackle
make sure you use the appropriate name of your entry pointAarau
(node:4132) ExperimentalWarning: The ESM module loader is experimental. internal/modules/run_main.js:54 internalBinding('errors').triggerUncaughtException( ^ Error [ERR_MODULE_NOT_FOUND]: Cannot find moduleCrackle
check this out, github.com/nodejs/node/issues/32103Aarau
It only working when you use nodemon. When use command "node index.js" then error still happen.Abortionist
SyntaxError: Named export 'Request' not found - ExpressJSOvarian
thankyou so much after hours of searching, this resolved the issueRibbing
C
9

I solved this with this approach:-

When You are using Es6 import/export functionality with node, you need to import modules with ".mjs" extensionand before importing rename your module ./path-to/app.js to ./path-to/app.mjs

and change your code to this

import http from 'http';
import app from './config/app.mjs'; //.mjs extension is necessary

const server = http.Server(app);
server.listen(3000, () => {
       return true;
});

and run your app.js with node --experimental-modules app.js

more on this https://nodejs.org/api/esm.html

Cupping answered 1/9, 2020 at 13:45 Comment(0)
H
4

I faced the same problem, and it got resolved when i removed the type:"module" from package.json

Hellgrammite answered 5/4, 2021 at 2:37 Comment(2)
If you remove "type":"module" from the package.json you will not be able to use imports in your node environmentRef
import/export only work if you set type to "module"Algin
T
3

As example import 'express' is resolved as ./node_modules/express/index.js.

In your case, create a folder called app with an index.js inside of it. After that you can import or require it using this line:

import app from './app/'
Tatouay answered 18/4, 2020 at 17:31 Comment(0)
M
3

I resolved this issue by below steps

  1. Install esm library

  2. Removed the type:"module" from package.json

  3. Added below command in package.json

    "scripts": {"start": "nodemon -r esm app/index.js"}

It's working for node 14 version

Masturbate answered 2/8, 2021 at 6:50 Comment(0)
I
2

I am using ts-node this way and works. Config ["type": "module"] in package.json, then update tsconfig.json to ts-node's ESM support and pass the loader flag to node in scripts, node --loader ts-node/esm ./index.ts. tsconfig.json:

{
  "compilerOptions": {
    "strict": true,
    "module": "ESNext", // ES2020
    "target": "ES2020",
    "moduleResolution": "Node",
    "lib": ["DOM", "DOM.Iterable", "ESNext"],
    "types": ["vite/client"],
    "jsx": "react-jsx",
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true
  },
  "ts-node": {
    "experimentalSpecifierResolution": "node",
    "transpileOnly": true,
    "esm": true,
  }
}
Intranuclear answered 31/8, 2023 at 15:20 Comment(2)
adding ts-node. experimentalSpecifierResolution works for meDorothadorothea
start using npx tsx, and stop using ts-node and fiddle useless and confusing tsconfig.sjonSievers
N
1

try changing the type using common, so import is changed to require

Nest answered 7/5, 2022 at 10:44 Comment(1)
Your answer could be improved by providing an example of the solution and how it helps the OP.Carbylamine
B
1

Add this to tsconfig.json

{
  "compilerOptions": {
  //...
  },
  "ts-node": {
    "esm": true,
    "experimentalSpecifierResolution": "node",
}
}
Byelostok answered 20/1, 2023 at 17:1 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Undo
M
0

If you used "type": "module", on package.json and then you should use import. while you are using import it required default so in router or related required file you must use like "export default serverRouter"

Or can follow the below syntax:

import express from "express"
const serverRouter = express.Router()

serverRouter.get("/", (req, res) => {
res.send("hello I'm runnig 4000")
})

export default serverRouter
Macle answered 15/7, 2022 at 8:56 Comment(0)
F
0

I had two version of Node v16.15.1 and v14.20.1. It was giving an Error in Node v14.20.1.

internal/process/esm_loader.js:74
    internalBinding('errors').triggerUncaughtException(

Solved it by switching to Node v16.15.1.

nvm use 16.15.1 # To switch to Node v16

nvm ls # Lists available Node versions

Flow answered 4/11, 2022 at 0:58 Comment(0)
C
0

if you are using es6 then your have to import all the file with file type

import app from './config/app.js';

not like

import app from './config/app';

Cohen answered 18/1, 2023 at 10:12 Comment(0)
S
0

In the new version of NodeJs you should import files with .Js extension otherwise it will facing the same error. I was facing the same issue when I import all files with .js then now it working fine.

Symbolism answered 17/6, 2023 at 4:8 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Undo
G
0

If your project is based on typescript / nodejs and you want:

  • your file extensions to be .ts
  • To use ES6 module import/export (instead of commonjs modules)
  • Not to add .js at the end of the module path

For example:

import x from "./y" 

Instead of:

import x from "./y.js" 

The complete config should be something like this:

  1. package.json:
{
  "type": "module",
  "scripts": {
    "start": "ts-node src/index.ts" 
     //make sure to use your own path to main file 
  },
}
  1. tsconfig.json:
{
  "compilerOptions": {
    "module": "ES2022",
    "target": "ES2022",
    "moduleResolution": "Node",
    "allowSyntheticDefaultImports": true
  },
  "ts-node": {
    "esm": true,
    "experimentalSpecifierResolution": "node"
  }
}

Then you can run your project with: npm run start

Gammy answered 23/7, 2023 at 10:11 Comment(0)
S
0

I started using npx tsx and removed tsconfig.json and everything just works for me.

Sievers answered 1/1 at 11:57 Comment(0)
G
-1

To resolve this error:

code: 'ERR_UNKNOWN_FILE_EXTENSION'

It's typically saying there is a need for an extension for ./bin/www file.

what you have to do is: add "type": "module", to your package.json and rename .bin/www to ./bin/www.js Restart your server

Gut answered 25/1, 2022 at 10:15 Comment(0)
G
-2

node:internal/errors:464 ErrorCaptureStackTrace(err); ^

Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:\projetos2\data-base-with-node\src\routes\index' imported from C:\projetos2\data-base-with-node\src\server.js at new NodeError (node:internal/errors:371:5) at finalizeResolution (node:internal/modules/esm/resolve:418:11)
at moduleResolve (node:internal/modules/esm/resolve:983:10) at defaultResolve (node:internal/modules/esm/resolve:1080:11) at ESMLoader.resolve (node:internal/modules/esm/loader:530:30)
at ESMLoader.getModuleJob (node:internal/modules/esm/loader:251:18)
at ModuleWrap. (node:internal/modules/esm/module_job:79:40) at link (node:internal/modules/esm/module_job:78:36) { code: 'ERR_MODULE_NOT_FOUND' }

Goldsmith answered 7/7, 2022 at 19:1 Comment(3)
import mainRouter from '../src/routes/index';Goldsmith
o meu funcionou depois que coloquei a extensão .jsGoldsmith
'assim' import mainRouter from '../src/routes/index.js';Goldsmith
R
-3

first of all install nodmodule :

1. npm install nodemodule --save

then :

2. npm run seed

Rhizo answered 27/11, 2021 at 10:0 Comment(0)
W
-7

was facing the same error. What worked for me was simply :

npm i
Weeper answered 28/9, 2021 at 12:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.