Home > OS >  Cannot import module: ERR_MODULE_NOT_FOUND
Cannot import module: ERR_MODULE_NOT_FOUND

Time:12-02

I'm trying to import a route.js file in my index.js file. I am exporting in the routes file and importing it in the index with .js extension. What am I missing here?

Folder structure:

Routes folder is in the server folder, same as index.js - accessible by a single . VsCode also highlights the location when typing, so that's not the issue.

routes.js:

import { registerUser } from '../controllers/userController'

const router = express.Router()


router.post("/", registerUser)


export default router;

index.js:

import mongoose from "mongoose";
import cors from "cors";
import dotenv from "dotenv";
import userRoutes from './routes/userRoutes.js'


dotenv.config();
const app = express();
app.use(cors());
app.use('/users', userRoutes)


const PORT = process.env.PORT;

mongoose
  .connect(process.env.CONNECTION_URL)
  .then(() => console.log("DB Connected"))
  .then(() =>
    app.listen(PORT, () => console.log(`Server is running on ${PORT}`))
  )
  .catch((error) => console.log(error.message)); 

CodePudding user response:

On the fourth import in the index.js file try removing the ".js" so it looks like this:

import userRoutes from './routes/userRoutes'

...if that file exists.

CodePudding user response:

try changing from

import userRoutes from './routes/userRoutes.js';

to

import userRoutes from './routes/routes.js';

If that doesn't work, can you share output of tree command or ls command in your root directory. As far as I am concerned. the .js extension would not be an issue in the import statement. So, if the naming part is okay. It's better to share error code with folder and naming structure in the question as well.

  • Related