Fixing “SyntaxError: Unexpected token” from Incorrect Import/Export
Common Causes
This error typically occurs when:
- Using incorrect import/export syntax
- Mixing different module systems (CommonJS vs ES modules)
- Missing file extensions in imports
- Using unsupported syntax in your environment
Solutions by Scenario
1. Basic ES Module Syntax
Correct:
// Named export
export const myFunction = () => {};
// Default export
export default myComponent;
// Named import
import { myFunction } from './module.js';
// Default import
import MyComponent from './MyComponent.jsx';
Incorrect:
// ❌ Mixing CommonJS and ES modules
const myFunction = require('./module'); // CommonJS
import { myFunction } from './module'; // ES Modules
2. For React Components
Correct:
// Component.jsx
const MyComponent = () => <div>Hello</div>;
export default MyComponent;
// App.jsx
import MyComponent from './Component.jsx';
Incorrect:
// ❌ Missing .jsx extension (depending on config)
import MyComponent from './Component';
3. TypeScript Specific Fixes
Correct tsconfig.json:
{
"compilerOptions": {
"module": "esnext",
"moduleResolution": "node",
"esModuleInterop": true
}
}
4. Node.js/CommonJS Projects
For pure CommonJS:
// Export
module.exports = { myFunction };
// Import
const { myFunction } = require('./module');
5. Dynamic Imports
Correct syntax:
const module = await import('./module.js');
Configuration Fixes
1. package.json Settings
{
"type": "module" // For ES modules in Node.js
}
2. Babel Configuration
// babel.config.js
module.exports = {
presets: [
['@babel/preset-env', { modules: 'auto' }]
]
};
3. Webpack Configuration
// webpack.config.js
module.exports = {
resolve: {
extensions: ['.js', '.jsx', '.json']
}
};
Debugging Steps
- Check file extensions – Add
.js
/.jsx
if missing - Verify module system – Consistent use of ES modules or CommonJS
- Inspect your build config – Babel/Webpack/TypeScript settings
- Check Node.js version – ES modules require Node 12+
- Look for syntax errors around the import/export statements
Common Error Patterns
// ❌ Using import in CommonJS file without transpilation
import fs from 'fs'; // In file without "type": "module"
// ❌ Mixing default and named exports incorrectly
export default const myVar = 42; // Incorrect
export const myVar = 42; // Correct named
export default 42; // Correct default
// ❌ Missing extension when needed
import './styles' // When should be './styles.css'