node.js – How do I enable import support in node js?

Question:

I'm writing a code

import create from './create'

And I have an error:

SyntaxError: Unexpected token import

I start the server like this

node server

You can add the node –experimental-modules server parameter AND rename the server.js file to server.mjs. But then require stops working.


Is it possible to somehow customize this default behavior? In order not to write unnecessary arguments. For both module and require to work?

Answer:

Excerpt from Node.js v10.8.0 documentation :

The --experimental-modules flag can be used to enable functions for loading ESM modules.

Once this is installed, files ending in .mjs will be loaded as ES modules.

 node --experimental-modules my-app.mjs
Scroll to Top