Resolve - node unexpected token import error


In this post, we will learn how to resolve node 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 do not support ES6 modules by default.

import express from "express";

// ERROR IN TERMINAL
SyntaxError: SyntaxError: Unexpected token import

Here are 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 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 which let you to use both require() and import() module 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.

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


💾 Recommended Articles