Skip to content

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 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.

→ Download my free Node.js Handbook!



You might be interested in those things I do:

  • Learn to code in THE VALLEY OF CODE, your your web development manual
  • Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
  • I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
  • Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
  • Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
  • Find me on X

Related posts that talk about node: