How to enable ES Modules in Node.js
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..
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.
download all my books for free
- javascript handbook
- typescript handbook
- css handbook
- node.js handbook
- astro handbook
- html handbook
- next.js pages router handbook
- alpine.js handbook
- htmx handbook
- react handbook
- sql handbook
- git cheat sheet
- laravel handbook
- express handbook
- swift handbook
- go handbook
- php handbook
- python handbook
- cli handbook
- c handbook
subscribe to my newsletter to get them
Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing flavio@flaviocopes.com. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.