'Node.js express.Router ERR_MODULE_NOT_FOUND when import the new routes

I am experiencing a weird error. I was just creating a new folder to separate my routes.

Inside I created the routes using the express.Router API and I exported the router itself.

Here is how the code looks like inside post-routes.ts:

import express from 'express';

const router = express.Router();

router.get( '/', ( req, res ) =>
{
    res.send( 'This is working' );
} );

export default router;

Ok. All I have to do now is to import it inside my index.ts and create a root route for my post-routes.ts file.

Please tell me if you see something wrong in my approach.

index.ts file:

import express from 'express';
import cors from 'cors';
import postRouter from './routes/post-routes';

const PORT = process.env.PORT || 5000;

app.use( '/posts', postRouter );


app.use( express.json( { limit: '30mb' } ) );
app.use( express.urlencoded( { limit: '30mb', extended: true } ) );
app.use( cors() );

app.listen( PORT, () => console.log( `listening at ${ PORT }` ) );

Good. Now to offer as much information as I possibly can, I will insert the following:

  1. File structure inside my project:

FILE STRUCTURE

  1. package.json file configuration:

PACKAGE.JSON FILE

As you can see, I am using the "type": "module" to be able to use import inside my node application. As for the typescript, I am getting no compiling errors, so index.ts sees the post-routes.ts file so I would expect that index.js would see post-routes.js file as well. But the server throws the error below. How can this be?

Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'E:\Github\hospytal-fasion\server\dist\routes\post-routes' imported from E:\Github\hospytal-fasion\server\dist\index.js



Solution 1:[1]

Apart from making sure that target and module are set to esnext in your tsconfig.json, make sure to include file extensions in your imports. i.e. try changing the following line:

import postRouter from './routes/post-routes';

to

import postRouter from './routes/post-routes.js';

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1