How to enable ES modules in Node.js

How do you enableimportSyntax in Node.js?

Many tutorials now useimport XXX from 'XXX'(ES module) Syntax instead ofconst XXX = require('XXX')(Plain JS) Syntax.

If you add it to a Node.js application, it will not work. You will receive the following error:

unexpected identifier error

unexpected identifier..

One of the solutions is to useTower of Babel. If you have already set up Babel settings for your project, then it should already work for you.

However, you no longer need Babel now, because Node has experimental support for ES modules, and since it is experimental, to enable it, you must do three things.

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

Second, add"type": "module"In your linepackage.jsonfile.

Third, use--experimental-modulesMark on callnodejs:

node --experimental-modules app.js

You should be good to go!

An alternative is to avoid adding"type": "module"In your linepackage.jsonFile instead of renaming yourapp.jsArchive (or other) toapp.mjs.

Please note that nowrequire()The grammar will stop working.

For older Node.js versions that may not support this flag, I suggest you checkesmnpm module.

Download mine for freeNode.js manual


More node tutorials: