0

I have a worker file with the following code

import * as Comlink from "https://unpkg.com/comlink/dist/esm/comlink.mjs";

const renderPDFInWorker = async (props) => {
  try {
    const { renderPDF } = await import("../renderPDF");
    return URL.createObjectURL(await renderPDF(props));
  } catch (error) {
    console.error(error);
    throw error;
  }
};

Comlink.expose({ renderPDFInWorker: renderPDFInWorker });

And custom hook to use said hook

import { useEffect, useState } from "react";
import { useAsync } from "react-use";
import { wrap } from "comlink";

const useRenderPDF = ({ text }) => {
  const [url, setUrl] = useState(null); // Initialize error as null
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null); // Initialize error as null

  useEffect(() => {
    const worker = new Worker("./worker/worker.js");
    const PDFWorker = wrap(worker);
    const fetchData = async () => {
      setLoading(true);
      try {
        const newUrl = await PDFWorker.renderPDFInWorker({ text });
        setUrl(newUrl);
        setLoading(false);
      } catch (e) {
        setError(e.message);
        setLoading(false);
      }
    };

    fetchData();

    return () => {
      // Cleanup function to terminate the worker
      worker.terminate();
    };
  }, [text]);

  useEffect(() => {
    // Cleanup previous URL when URL changes
    return () => {
      if (url) {
        URL.revokeObjectURL(url);
      }
    };
  }, [url]);

  return {
    url,
    loading,
    error,
  };
};

export default useRenderPDF;

Now the problem is that when i do this i get this error:

Uncaught SyntaxError: Unexpected token '<'

Now reading i saw that you should move the worker to public folder. I did it but then i get error as i can't use import outside modules. So i went to the html file and added this

But even so I still get the import error

Does anyone understanbd what is happening here? Or how to fix it?

1 Answer 1

0

Which bundler are you using? in Vite for example you could use https://vite.dev/guide/features.html#web-workers

const worker = new Worker(new URL('./worker.js', import.meta.url))

or

import MyWorker from './worker?worker&inline'

to create an inline worker.

With esbuild you can try this plugin

with Webpack is almost the same as Vite

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.