Skip to content

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

@uttk

Description

@uttk

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/quickjs-emscripten@0.31.0';

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>

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions