Search code examples
typescriptnext.jsweb-workertsconfig

How to compile a .ts file to .js in a Next.js project (to use it as a Web worker)?


I have a TypeScript Next.js project:

  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },

I want to add to it a Web worker. I know that the worker is started like new Worker("worker.js").

What is the correct way to produce the .js file from worker.ts?

I could call tsc directly, but I am not sure that it is the right way, that I integrate it into package.json scripts correctly, and whether it uses tsconfig.json.


Solution

  • You don't need compile ts to js. Just import the worker by

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

    Here is example for you.