Resolve – node unexpected token import error in Nodejs

In this post, we will learn how to resolve the “SyntaxError: Unexpected token import” error in node applications.

The unexpected token error occurs when you try to work with ES6 modules, import / export statement in your node application. This is because node currently does not support ES6 modules by default.

import express from "express";

SyntaxError: Unexpected token import

Here are a few fixes that can help to resolve the error.

Using require() instead of import()

This is a very easy fix to the problem. We just have to use the require instead of import.

const express =  require("express");

However, if you want to import only then follow the solutions below.

Using .mjs extension and experimental flag

If you are on node 9, then you have to enable --experimental-modules flag and use the .mjs file extension and run:

node --experimental-modules app.js

If you are using node 12, then you can either use .mjs file extension or set { "type" : "module" } in your package.json file.

  "type": "module",
  "name": "myApp",
  "version": "1.0.0",
  "description": "",
   "scripts": {
    "start": "node app.js"

And then run node application with the --experiment-modules flag.

In node 13, you can either use .mjs file extension or set { "type" : "module" } in package.json file.

You DO NOT have to run the --experimental-modules flag in node 13.

Using .esm node package

This is a small package that let you to use both require() and import() modules in our node application.

Using esm module you do not have to use any flag or change any file extension in your application.

Just install the esm package in your project by,

npm install --save esm

And then update your start script in your package.json file to

node -r esm app.js

Well, that’s it. Now you can work on your project with no unexpected token import error.

Conclusion: Since most people now use Node 13 or above, you can just set type="module" in your package.json file and it will fixed the error.

Related Topics:

(Solve) Npm WARN Package.Json: No Repository Field

Resolve Npm Cannot Find Module Error In Nodejs

How To Fix “Npm ERR Cb() Never Called” | Quick Fix