'import' and 'export' may only appear at the top level

avatar
Borislav Hadzhiev

Last updated: Mar 7, 2024
2 min

banner

# 'import' and 'export' may only appear at the top level

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.

import and export may only appear at the top level

Here is an example of how the error occurs.

App.js
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.

This could be a missing parenthesis as well, so make sure the functions and classes you have defined are syntactically correct.

Once we add the closing curly brace, the error is resolved.

App.js
const App = () => { return ( <div> <h1>Hello world</h1> </div> ); }; export default App;

# Don't mix up default and named exports and imports

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:

index.js
// ๐Ÿ‘‡๏ธ default export export default function sum(a, b) { return a + b; }

And import the function in the other file.

another-file.js
// ๐Ÿ‘‡๏ธ 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.

You can only have 1 default export per file.

Here's how you use named imports/exports.

index.js
// ๐Ÿ‘‡๏ธ named export export function sum(a, b) { return a + b; }

And now we use a named import in the other file.

another-file.js
// ๐Ÿ‘‡๏ธ 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 have to be consistent with your imports and exports. Don't use curly braces when importing default exports, and use curly braces when importing named exports.

You can also mix and match, here's an example.

index.js
// ๐Ÿ‘‡๏ธ named export export const num = 100; // ๐Ÿ‘‡๏ธ default export export default function sum(a, b) { return a + b; }

And here are the imports.

another-file.js
// ๐Ÿ‘‡๏ธ 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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev