Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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
11,125 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?