163

I am trying to use a plugin called "Simplebar" found on GitHub, GitHub SimpleBar but after downloading the scripts and looking at the simple.js script, it looks like it has an error

"SyntaxError: import declarations may only appear at top level of a module"

At the top of the simplebar.js file there are some import lines of code:

import scrollbarWidth from 'scrollbarwidth'
import debounce from 'lodash.debounce'

import './simplebar.css'

If I look in my browser debugger I see an error: "SyntaxError: import declarations may only appear at top level of a module".

Has anyone tried to us this plugin?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
DCJones
  • 3,121
  • 5
  • 31
  • 53

1 Answers1

208

I got this on Firefox (FF58). I fixed this with:

  1. It is still experimental on Firefox (from v54): You have to set to true the variable dom.moduleScripts.enabled in about:config

Source: Import page on mozilla (See Browser compatibility)

  1. Add type="module" to your script tag where you import the js file

<script type="module" src="appthatimports.js"></script>

  1. Import files have to be prefixed (./, /, ../ or http:// before)

import * from "./mylib.js"

For more examples, this blog post is good.

Eric M.
  • 2,507
  • 2
  • 10
  • 15
  • 13
    Tried both. Neither worked – a.anev Jul 16 '21 at 21:09
  • 32
    The `type="module"` fixed this for me. – Kipton Barros Nov 22 '21 at 05:14
  • 1
    I am not sure if this is the right answer because if Firefox is involved, why the sample html is working fine and Firefox does not show the same error ("SyntaxError: import declarations may only appear at top level of a module") at that page ? – Igor Laszlo Jan 30 '22 at 18:12
  • It worked for me. Double check (how) the imports/exports you're using. https://javascript.info/import-export – carloswm85 Jun 25 '22 at 02:31
  • After being sure all these steps were applied I was still having this import/export error, or even others (which I sadly haven't recorded anywhere, some of errors were `Uncaught ReferenceError : funcName not defined` or something ). Fixed when I **moved all functions/classes declarations on top-level**, *outside of any code block*. Hope this can help fix anyone with the same rookie mistake – tebkanlo Sep 21 '22 at 08:06
  • Is firefox fixed yet? I'm still seeing it. – chovy Feb 16 '23 at 11:21
  • @chovy Experimental ES-Module support was added last week for workers in Firefox v111. The user still needs to explicitly activate the feature. See the following table: https://developer.mozilla.org/en-US/docs/Web/API/Worker#browser_compatibility Also, see this vite issue which has more info about it: https://github.com/vitejs/vite/issues/8621 – tofindyou Mar 21 '23 at 13:49
  • Moreover, functions imported from a js file with `type=module` are not recognized by the browser, I had to explicitly set it global in the `.js` using `window.function_to_use= function_to_use` – younes zeboudj Jun 29 '23 at 13:44