DMantas
DMantas

Reputation: 153

can't export routes in express with ES6

I was writing the backend for my project. I have noticed that it was getting really messy and was repeating a lot of code over and over again. I decided to re-write everything and use classes. I also took the decision to use ES6 modules for imports. The first bump I have ran into is that I can't seem to get my routes working.

import express from 'express';
export const router = express.Router();

router.post('/test', async (req, res) => {
   'test'
});


Importing it into server.js

import { router } from './routes/user.route'
server.use(router)

The error I get

Cannot find module

Upvotes: 0

Views: 1225

Answers (2)

Karunakar
Karunakar

Reputation: 11

Try to import with a fully qualified name with extension.

import { router } from './routes/user.route.js'

Upvotes: 0

jsejcksn
jsejcksn

Reputation: 33881

ES modules require literal specifiers (there is no magic resolution for extensionless names like in CJS).

In your original import statement, the specifier points to a module that doesn't exist (there is no file named user.route — its name is user.route.js):

import { router } from './routes/user.route'

Instead, you must provide the full path (including the extension):

import { router } from './routes/user.route.js'

See more at Mandatory file extensions - Modules: ECMAScript modules | Node.js Documentation

Upvotes: 1

Related Questions