Skip to content

How to enable ES Modules in Node.js

New Course Coming Soon:

Get Really Good at Git

How do you enable the `import` syntax in Node.js?

Many tutorials now use the import XXX from 'XXX' (ES Modules) syntax instead of const XXX = require('XXX') (CommonJS) syntax.

If you add that to your Node.js app, it won’t work. You’ll get an error like this:

unexpected identifier error

unexpected identifier..

One of the solutions to this is to use Babel. If you already have a Babel setup for your project, this should already be working for you.

But you shouldn’t need Babel any more now because Node has experimental support for ES Modules, and since it’s experimental, to enable it you must do 3 things.

First, install the latest version of Node.js. It has the latest and greatest features.

Second, add the "type": "module" line in your package.json file.

Third, use the --experimental-modules flag when invoking nodejs:

node --experimental-modules app.js

You should be good to go!

An alternative is to avoid adding the "type": "module" line in your package.json file and instead rename your app.js file (or whatever) to app.mjs.

Note that now the require() syntax will stop working.

For older Node.js versions that might not support this flag, I recommend checking out the esm npm module.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my Node.js Handbook
→ Read my Node.js Tutorial on The Valley of Code

Here is how can I help you: