Last updated: Mar 7, 2024
Reading timeยท2 min
The error "import and export may only appear at the top level" occurs when we forget a closing brace when declaring a function or class, or mix up default and named exports and imports.
To solve the error, make sure you haven't forgotten a closing brace in a function's definition.
Here is an example of how the error occurs.
const App = () => { return ( <div> <h1>Hello world</h1> </div> ); // ๐๏ธ missing curly brace here // โ๏ธ SyntaxError: 'import' and 'export' may only appear at the top level. (11:0) export default App;
We have a missing curly brace in the definition of the App
function which
caused the error.
Once we add the closing curly brace, the error is resolved.
const App = () => { return ( <div> <h1>Hello world</h1> </div> ); }; export default App;
Another common cause of the error is mixing up default and named exports and imports.
You can use default imports/exports with ES6 modules in the following way:
// ๐๏ธ default export export default function sum(a, b) { return a + b; }
And import the function in the other file.
// ๐๏ธ default import import sum from './index.js'; console.log(sum(10, 15));
Notice that we do not use curly braces when working with default imports.
Here's how you use named imports/exports.
// ๐๏ธ named export export function sum(a, b) { return a + b; }
And now we use a named import in the other file.
// ๐๏ธ named import import {sum} from './index.js'; console.log(sum(10, 15));
Notice the curly braces, this is how we import a named export.
You can also mix and match, here's an example.
// ๐๏ธ named export export const num = 100; // ๐๏ธ default export export default function sum(a, b) { return a + b; }
And here are the imports.
// ๐๏ธ default and named imports import sum, {num} from './index.js'; console.log(sum(10, 15)); // ๐๏ธ 25 console.log(num); // ๐๏ธ 100
We used a default import to import the sum
function and a named import to
import the num
variable.