quickjs-emscripten icon indicating copy to clipboard operation
quickjs-emscripten copied to clipboard

How to use quickjs-emscripten inside an ESM Service Worker?

Open uttk opened this issue 8 months ago • 0 comments
trafficstars

I'm trying to use quickjs-emscripten inside a Service Worker that is written as an ECMAScript module (ESM). However, it fails to execute due to the use of dynamic import() inside the library.

Since dynamic imports are not allowed in Service Workers, is there any workaround to make quickjs-emscripten work in this environment?

example:

// worker.js
import { getQuickJS } from 'https://esm.sh/[email protected]';

async function main() {
  const QuickJS = await getQuickJS()
  const vm = QuickJS.newContext()

  const world = vm.newString("world")
  vm.setProp(vm.global, "NAME", world)
  world.dispose()

  const result = vm.evalCode(`"Hello " + NAME + "!"`)

  if (result.error) {
    console.log("Execution failed:", vm.dump(result.error))
    result.error.dispose()
  } else {
    console.log("Success:", vm.dump(result.value))
    result.value.dispose()
  }

  vm.dispose();
}

main();
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Quick.js Example in Service Worker</title>
</head>
<body>
  <script>
    navigator.serviceWorker.register("/worker.js", { scope: "/", type: "module" });
  </script>  
</body>
</html>

uttk avatar Feb 23 '25 04:02 uttk