Node.js – SyntaxError: Unexpected token import

Node 13+ Since Node 13, you can use either the .mjs extension, or set {"type": "module"} in your package.json. You don’t need to use the --experimental-modules flag. Modules is now marked as stable in node.js

Node 12 Since Node 12, you can use either the .mjs extension, or set "type": "module" in your package.json. And you need to run node with the --experimental-modules flag.

Node 9 In Node 9, it is enabled behind a flag, and uses the .mjs extension.

node --experimental-modules my-app.mjs

While import is indeed part of ES6, it is unfortunately not yet supported in NodeJS by default, and has only very recently landed support in browsers.

See browser compat table on MDN and this Node issue.

From James M Snell’s Update on ES6 Modules in Node.js (February 2017):

Work is in progress but it is going to take some time — We’re currently looking at around a year at least.

Until support shows up natively (now marked stable in Node 13+), you’ll have to continue using classic require statements:

const express = require("express");

If you really want to use new ES6/7 features in NodeJS, you can compile it using Babel. Here’s an example server.

Leave a Comment