The ‘Unexpected token import’ error in Node.js occurs when you’re trying to use the ES6 import syntax without the proper configuration. Node.js versions below 13.2.0 don’t support ES6 imports by default and need to be transpiled with Babel, or you need to use the CommonJS require
syntax. However, newer versions of Node.js do support ES6 imports if you use the .mjs
extension or set "type": "module"
in your package.json
.
Reasons Behind the Error
- Using ES6 import/export syntax in a Node.js environment that doesn’t recognize it natively.
- Incorrect configuration for ES6 modules in your Node.js project.
Steps to Fix the Error
1. Use CommonJS Syntax
Replace all your import statements with the CommonJS require syntax.
const express = require('express');
const app = express();
app.listen(3000, () => {
console.log('Server running on port 3000');
});
2. Update Node.js
Ensure you’re using a Node.js version that supports ES6 modules, which is 13.2.0 or higher.
3. Use the .mjs Extension
Rename your file with an .mjs
extension if you want to use import/export syntax.
4. Set “type”: “module” in package.json
Add the following line to your package.json
to treat all .js files as ES modules:
{
"type": "module"
}
Complete Code Example
Using ES6 import syntax with updated Node.js version or proper configuration:
// save as example.mjs or ensure "type": "module" is set in package.json
import express from 'express';
const app = express();
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Alternative Solution: Use Babel
If updating Node.js is not an option, you can transpile your code using Babel to convert ES6 imports to CommonJS. Install Babel packages and configure Babel to transpile your ES6 code.