skip to Main Content

My Nuxt 3 app needs to run some possibly heavy string-related calculations so I want to move them in worker:

// /assets/workers/test.ts

// import someStuff from "my-package-in-node_modules"

console.log('Hello from worker!');

onmessage = () => {
    /* Do stuff... */
}

This is how I add worker on my Vue page:

<script setup lang="ts">
    import MyWorker from "~/assets/workers/test?worker";

    const worker = new MyWorker();
</script>

However, when I try to open the page it shows an 500 error followed with Worker is not defined message.

My guess is that it fails to create worker on server side and throws an error. So maybe I need to somehow run this part of code only on client side.

How can I fix this?

2

Answers


  1. Chosen as BEST ANSWER

    Since Nuxt can't create workers on server side, the worker has to be created on client side:

    if (process.client)
    {
        const worker = new MyWorker();
    }
    

  2. If you opened SSR (or by default) in nuxt.config.ts, <script setup> will run on server side. That’s why Worker is not defined.

    You can do like this:

    onMounted(async () => {
      const MyWorker = await import("~/assets/workers/test?worker");
      const worker = new MyWorker();
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search