How to fix: import and export may only appear at the top level

So I’ve setup a new Svelte project and install all the latest node modules.

As I was setting up my project with a third party library and received this error message:

1: /* global window */
2: import ponyfill from './ponyfill.js';
4: var root;
Error: 'import' and 'export' may only appear at the top level

If you’re developing a Svelte project, you’re probably using rollup as your compiler.

If that is the case, here’s how to solve that problem.

This problem is because of @rollup/plugin-commonjs version. It seems that version 11.1.0 has a bug.

Solution: Downgrade @rollup/plugin-commonjs to 11.0.2

I’ve had to downgrade the module library version. Just run this command in your terminal:

npm i -D @rollup/plugin-commonjs@11.0.2

I like to tweet about Svelte and post helpful code snippets. Follow me there if you would like some too!