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.
Here is how can I help you:
- COURSES where I teach everything I know
- THE VALLEY OF CODE your web development manual
- BOOTCAMP 2024 cohort in progress, next edition in 2025
- BOOKS 16 coding ebooks you can download for free on JS Python C PHP and lots more
- SOLO LAB everything I know about running a lifestyle business as a solopreneur
- Interesting links collection
- Follow me on X