developit / workerize-loader

🏗️ Automatically move a module into a Web Worker (Webpack loader)

Home Page:https://npm.im/workerize-loader

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

ReferenceError: regeneratorRuntime is not defined

Enitoni opened this issue · comments

commented

I'm trying to use this library with Babel and TypeScript, but I'm getting a weird error.

// queue.worker.ts

import { TrackData } from "modules/track/types"
import { shuffleArray } from "common/lang/array/helpers/shuffleArray"

export async function getShuffledTracks(tracks: TrackData[], active: number) {
  return shuffleArray(tracks).sort((track) => (track.id === active ? -1 : 0))
}
// somewhere.ts

import * as QueueWorker from "../queue.worker"
const worker = (QueueWorker as any)() as typeof QueueWorker

//  somewhere in the file
await worker.getShuffledTracks(...)

Then, when the function is called, I get this error:
image

This is what the config for the loader looks like:

const workerRule = {
  test: /\.worker\.ts$/,
  use: [
    "workerize-loader",
    {
      loader: "babel-loader",
      options: {
        presets: [
          [
            "@babel/env",
            {
              modules: false,
            },
          ],
        ],
      },
    },
  ],
}

So from what I understand, for webpack to let your code use async, your code needs to explicity import a polyfill. My current code is using babel/polyfill, but I believe that's been deprecated so maybe try https://github.com/facebook/create-react-app/tree/master/packages/react-app-polyfill instead?

Knowing that workers and your main thread are completely seperate, it's reasonable to assume you'd need to do this in your worker code too. So I added import '@babel/polyfill'; as the very first line of my worker file. This seems to have worked, but I don't guarantee this is the proper fix.

tl;dr Try adding import '@babel/polyfill'; or import 'react-app-polyfill/ie11'; import 'react-app-polyfill/stable'; as the very first line of your worker file.

Yup, make sure to import a polyfill your code depends on.

What about typescript? There's still a similar error there

import regenerator in your worker file:

// foo.worker.ts
import 'regenerator-runtime';

// your code