I've built an AudioWorklet that imports an npm module. This works during runtime but fails when compiled. My understanding (but new to Worklets and Web Workers) is that the AudioWorklet code needs to be self-contained and can't pull the import in production.
Can we compile the AudioWorklet with the npm imports at build time (or something else of better practice)? Using Vite for frontend compilation.
The following is a simplified example of my Worklet, but no real code to shorten the example.
import { ToolWASM } from 'tool/dist/wasm.es.js'
import Tool from 'tool/dist/core.es.js'
let tool = new Tool(ToolWASM)
class SampleProcess extends AudioWorkletProcessor {
constructor() {
super()
this.tool = tool
}
process() {
this.tool.doSomething()
return false
}
}
registerProcessor('sample-processor', SampleProcess)
From my attempts to do a similar trick with vite simply
ctx.audioWorklet.addModule(new URL('./worklet.ts', import.meta.url))
does the job at least in development build.To make it really work it should be handled as per vite's docs for workers. See import with query suffixes