Reputation: 278
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:
package.json
file configuration: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
Upvotes: 2
Views: 4567
Reputation: 1
Change the format from
import userRouter from "./routes/users";
to
import userRouter from "./routes/users.js";
it's work for me 🙌
Upvotes: 0
Reputation: 128
you have to import "./routes/post-routes.js" (here ".js" needed)
if you use old require methos you don't need need .js you only need require("./routes/post-routes")
Upvotes: 1
Reputation: 20424
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';
Upvotes: 5