Home > Back-end >  How can I use a library in a JS file for my HTML project?
How can I use a library in a JS file for my HTML project?

Time:02-28

I'm trying to use a lib called ToneJS in my project, in a way that i've could write a button that would apply an reverb effect or increase the pitch of some audio for example.

in my HTML file I'm importing the JS file that is going to have the scripts in a tag

<html>
...
   <script src="tone.js"></script>

and in the tone.js file I have only the import line by now:

import * as Tone from "./node_modules/tone";

but there's my problem: inside the console I got the message: Uncaught SyntaxError: Cannot use import statement outside a module

I tried adding the "type": "module" in the package.json of the project, but nothing happened. Then I changed the type="module" inside the <script> tag inside the HTML file, but another different error appeared:

Failed to load module script: Expected a JavaScript module script but the server responded
with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts
per HTML spec.

CodePudding user response:

If you are using ES6 modules you should use type="module" in your <script> tag so you should use your script tag as below:

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

there is some example here:

<!doctype html>
<html>
<script type="module">
  import * as Tone from "./node_modules/tone";

  //do something with Tone
</script>

CodePudding user response:

If your script is a module, you must do this:

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

Or else the system will think it's normal JavaScript, and that error will occur.

  • Related