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
Since Nuxt can't create workers on server side, the worker has to be created on client side:
If you opened SSR (or by default) in
nuxt.config.ts
,<script setup>
will run on server side. That’s whyWorker
is not defined.You can do like this: