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

Hi there,
I’m using WP and I’m trying to install Three.js via NPM.
My package is well instaled in my node_modules folder, wich is in the root of my global WP folder.
When I try to call THREE in my js script: import THREE from “three”;
it’s telling me “import declarations may only appear at top level of a module”

I’m calling my js script in my footer:
I also have this same message when i call it from my footer.
I tought that it come from the fact that my scripts ws called before my module but think I don’t understand well the problem…
Can somewone help me to understand and solve my problem plzz ?

You can either:

  1. Use a CDN - [as in this example in the HTML tag]. Then you don’t need to import three, it’ll be available automatically in the global scope as THREE.
  2. Use import maps pointing to your node_modules three bundle. Then add type="module" to your <script> (example.) Kepp in mind - scripts of type module do not have direct access to the global scope variables - they are limited to themselves and whatever they import.
  3. Use a bundler and transform modules into static JS build. Although it may be unnecessarily complex in this case to add a bundler to a WP build.

Thanks for your answer, it’s helped me to see clearly !
I finally succeed to compile my project correctly,
For the record I used prepros wich bundle JS with imports and requires, it’s work very fine with WP