简体   繁体   中英

Cannot import module: ERR_MODULE_NOT_FOUND

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)); 

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM