Introduction
The Unexpected Token 'import'
error is common in Node.js when working with ES6 modules. This issue typically arises due to a mismatch between the module system being used (CommonJS vs ES6). In this blog, we will explain the causes of the error and provide simple solutions.
Why Does the “Unexpected Token ‘import'” Error Occur?
Node.js traditionally uses the CommonJS module system, which relies on the require
syntax. However, ES6 introduced import
and export
syntax, which is not supported by default in older Node.js versions or without proper configuration.
The error occurs when Node.js encounters an import
statement it cannot process.
Error Example
SyntaxError: Unexpected token 'import'
This typically happens when you try to run the following code:
// File: index.js
import express from 'express';
const app = express();
Solutions for “Unexpected Token ‘import'”
Here are some effective ways to resolve this error:
1. Update Your Node.js Version
Ensure you are using Node.js version 12 or higher, as these versions support ES6 modules with some configurations. Run the following command to check your Node.js version:
node -v
If you have an older version, update Node.js by downloading the latest version from the official website.
2. Use the type
Field in package.json
To enable ES6 modules in your project, set the type
field in your package.json
file to module
:
{
"type": "module"
}
This allows Node.js to recognize import
and export
statements.
3. Use .mjs
File Extension
Rename your JavaScript files to have a .mjs
extension instead of .js
. Node.js treats .mjs
files as ES6 modules by default.
4. Stick to require
Syntax
If you don’t need ES6 modules, revert to the CommonJS syntax by replacing import
with require
:
// Replace this:
import express from 'express';
// With this:
const express = require('express');
5. Use a Transpiler (e.g., Babel)
If you want to use ES6 modules in older Node.js versions, configure Babel to transpile your ES6 code to CommonJS. Install Babel and configure it as follows:
npm install --save-dev @babel/core @babel/cli @babel/preset-env
Create a .babelrc
file with this content:
{
"presets": ["@babel/preset-env"]
}
Then transpile your code with:
npx babel src --out-dir dist
Conclusion
The “Unexpected Token ‘import'” error occurs when Node.js encounters ES6 syntax it doesn’t recognize. By updating your Node.js version, using the type
field, or sticking to CommonJS syntax, you can easily resolve this issue. For larger projects, a transpiler like Babel may be necessary.
With these solutions, you can confidently use ES6 modules in your Node.js applications.