'Tone.js with ESM modules

I am trying to use tone.js on ESM modules. (I could use it without problems in “commonjs” with a bundler)

In the html I have

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

and tests.js:

import * as Tone from "./Tone.js"  

gives -> Tone.Gain is not a constructor

If I try:

import * as Tone from "./node_modules/tone/build/esm/index.js";

then Chrome shows status 404 Global not found, and the same for classes, version, ToneAudioBuffer, AudioContext, ToneAudioBuffers andToneBufferSource

(Maybe I am wrong, just starting with ESM modules, but digging into that esm/index.js the imports are like import { ToneAudioBuffer } from "./core/context/ToneAudioBuffer"; (without .js extension, shouldn’t have any ESM module explicitly add the extension?)

I’ve lost track of other combinations I have tried without success and I can not find a working example of a such project. What would be the right way - if possible- to run Tone.js on js modules?



Solution 1:[1]

Without bundling, serving a HTML with a module script, try import "./node_modules/tone/build/esm/index.js";.

Or use a build of some kind, then use the recommended import import * as Tone from "tone";.

Optionally, use the CDN, with the plain global <script src="https://unpkg.com/[email protected]/build/Tone.js"></script> or the module syntax above.

<script type="module">
import "https://unpkg.com/[email protected]/build/Tone.js";

const btn = document.querySelector("button");
btn.addEventListener("click", async () => {
  await Tone.start();
  const synth = new Tone.Synth().toDestination();
  const now = Tone.now();
  synth.triggerAttack("C4", now);
  synth.triggerRelease(now + 50);
});
</script>
<button>Play</button>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jsejcksn