Import and export may only appear at the top level

The error "import and export may only appear at the top level" may occur due to a missing closing brace when declaring a function or class or mixing up default and named exports and imports.

Let's take an example of the below code.

// This code throws error
function App() {
  	return (
  		<div>
    		<p>Hi there!</p>    	
    	</div>
  	);
// Here we have missing closing braces
export default App;

In the above code, you may notice that the closing braces of the app function were missing. This caused the above error. We can add the closing braces and thus the error was resolved in the below code. The same error will be shown even if we are working with class components.

Solution:

function App() {
  	return (
  		<div>
    		<p>Hi there!</p>    	
    	</div>
  	);
}

export default App;

How to find the missing braces in the code

You can find such errors very quickly if you are using any modern IDE like visual studio code or simply VSCode. It will show the error that a curly brace is expected at the end. VSCode will show one error and if you hover the cursor over it, it will show a message like “The parser expected to find a ‘}’ to match the ‘{’”. The code formatting (prettier or the default code format) will not work if we have braces missing in the code.

Conclusion

To fix React error “import and export may only appear at the top level”, check whether we have any missing closing braces in our code.