Explore Bato Web Agency Webflow Certified Partner Profile Explore Bato Web Agency Webflow Certified Partner Profile

SyntaxError: import declarations may only appear at top level

Illustration without a description Illustration without a description

A static import declaration appeared inside a function, conditional or other nested block. JavaScript modules allow those declarations at module scope. Moving the declaration above the function solves the syntax error when the dependency should be available whenever the module loads.

 

If the import is meant to happen only after a user action or a condition, use the import() expression and handle its Promise in that path. Make sure the containing file is loaded as a module if it also uses static imports.

 

Move a dependency needed on every run to module scope. For a conditional import, also test the branch that skips it and the branch that waits for it. The code that uses the imported value needs to wait for the Promise.

 

import { parse } from './parser.js'; function load() { return parse('42'); }

 

Find the block around the import and decide whether that dependency should load at startup or only when the block runs.