Error: AudioWorkletNode is undefined in React App

3.2k views Asked by At

I'm trying to create an AudioWorklet in React. I'm using create-react-app and importing scripts that are working outside the context of React into App.jsx. It is failing to instantiate my AudioWorkletNode extension and throwing the following error:

   Failed to compile.
./src/worklet/worklet-node.js
  Line 2:  'AudioWorkletNode' is not defined  no-undef

The code:

 // The code in the main global scope.
    class MyWorkletNode extends AudioWorkletNode {
        constructor(context) {
          super(context, 'my-worklet-processor');
        }
      }

      let context = new AudioContext();

      context.audioWorklet.addModule('processor.js').then(() => {
        let node = new MyWorkletNode(context);
      });

The same exact code is successfully initializing the AudioWorklet, so I'm a little baffled as to why AudioWorkletNode is not being recognized.

2

There are 2 answers

6
Dan Abramov On

Create React App is configured to enforce that you access browser APIs like this with a window. qualifier. This way it's clear you're using a global, and didn't forget to import something (which is very common).

This should work:

class MyWorkletNode extends window.AudioWorkletNode {
0
Luca Capra On

I used @types/audioworklet to obtain proper definitions

npm i -D @types/audioworklet

Check in the README if you need extra configuration steps to have it properly hooked in tsconfig.json (in my case it just worked)