JavaScript Build a Simple Dynamic Site with Node.js Handling Routes in Node.js User Route

Require is not defined in ES module scope.

I get Error in my terminal when i try to use require() function, they rather ask me to use import but i still get error when i try the import function too

3 Answers

Rachel Johnson
STAFF
Rachel Johnson
Treehouse Teacher

Hey khaper bas22 , thanks for sharing your question!

I understand you're encountering issues with require in your Node.js project related to ES modules. This can happen due to several reasons, and I'd be happy to help troubleshoot. If you are using Treehouse Workspaces, it is usually configured to work with the course. However, if you are working locally, there might be some environmental differences between your machine and the teacher's. Here are some common issues and solutions:

  1. Node.js Version: Ensure you are using a Node.js version that supports ES modules without the need for the --experimental-modules flag. Versions from 14.0.0 onward fully support ES modules.

  2. package.json Configuration: Set the "type" field in your package.json to "module" to indicate the use of ES modules:

    {
    "type": "module"
    }
    

Unfortunately, that's all I can offer at the moment as I'm unsure of what you're seeing and how Node.js has been set up on your machine. If you can provide more specific details, code snippets, or error messages, I can give more targeted assistance!

the version of my node is v21.7.2 and i am working locally on my computer. when i run the code i got a referenceError :require is not defined in ES module scope, you can use import instead.

Darian Ross
Darian Ross
13,223 Points

I'm getting the same "tip" from VS Code that using import and export is more secure and up to date that using require and module.exports. Should we just keep going with this older standard?