N Kaushik

Fix- import and export may only appear at the top level

June 26, 2022

import and export may only appear at the top level:

This error pops up if you forget to close the curly bracket {} in a function or class component. While merging git conflicts, there is a high possibility to catch this error. Always reverify your code if you see this error. Modern IDE like VSCode will show this before you run your project. If you use VSCode to develop, you will find it easily.

For example,

const App = () => {
  return (
    <div>
      <p>Hello World</p>
    </div>
  );

export default App;

It will throw this error, import and export may only appear at the top level. We missed a curly brace. It should be:

const App = () => {
  return (
    <div>
      <p>Hello World</p>
    </div>
  );
};

export default App;

If you use a class component, it will throw the same error.

How to find the error:

You can find it sooner 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 the error:

VSCode will show one error and if you hover the cursor over it, it will show the below error message:

import export error

Code format will not work in VSCode:

Code formatting will fail on VSCode. If you are using prettier or the default code formatter, it will fail to format the code.

The easiest way to fix this error is to recheck the files that you have modified recently.


Subscribe to my Newsletter