How to make web workers with TypeScript and webpack

不羁的心 提交于 2020-01-28 03:47:05

问题


I'm having some issues with properly compiling my typescript when I attempt to use web workers.

I have a worker defined like this:

onmessage = (event:MessageEvent) => {
  var files:FileList = event.data;
    for (var i = 0; i < files.length; i++) {
        postMessage(files[i]);
    }
};

In another part of my application i'm using the webpack worker loader to load my worker like this: let Worker = require('worker!../../../workers/uploader/main');

I'm however having some issues with making the typescript declarations not yell at me when the application has to be transpiled. According to my research i have to add another standard lib to my tsconfig file to expose the global variables the worker need access to. These i have specified like so:

{
     "compilerOptions": {
          "lib": [
               "webworker",
               "es6",
               "dom"
          ]
     }
}

Now, when i run webpack to have it build everything i get a bunch of errors like these: C:/Users/hanse/Documents/Frontend/node_modules/typescript/lib/lib.webworker.d.ts:1195:13 Subsequent variable declarations must have the same type. Variable 'navigator' must be of type 'Navigator', but here has type 'WorkerNavigator'.

So my question is: How do I specify so the webworker uses the lib.webworker.d.ts definitions and everything else follows the normal definitions?


回答1:


In your tsconfig.json file, in compilerOptions set this:

{
    "compilerOptions": {
        "target": "es5",
        //this config for target "es5"
        "lib": ["webworker", "es5", "scripthost"]
        //uncomment this for target "es6"
        //"lib": ["webworker", "es6", "scripthost"]
    }
}

Web workers can't access to DOM, window, document and parent objects (full list supported objects here: Functions and classes available to Web Workers); the dom lib of TypeScript is not compatible and redefine some elements that are define in lib.webworker.d.ts




回答2:


Using batressc' answer I have managed to actually get passing messages back and forth working, in a somewhat nice manner.

Adding to his answer with the libs, the Typescript code also needs some nudges to get working.

First, create a file to make the file-loader cooperate with you when importing. I have a file named file-loader.d.ts with the following contents:

declare module "file-loader?name=[name].js!*" {
    const value: string;
    export = value;
}

Next, in your main.ts import the worker using the fileloader:

import * as workerPath from "file-loader?name=[name].js!./test.worker";

This workerPath can then be used to create the actual worker:

const worker = new Worker(workerPath);

Next, create the actual worker file, test.worker.ts, with the following content:

addEventListener('message', (message) => {
    console.log('in webworker', message);
    postMessage('this is the response ' + message.data);
});

You can then send messages back and forth in the main.ts file:

worker.addEventListener('message', message => {
    console.log(message);
});
worker.postMessage('this is a test message to the worker');

I have gathered everything in a github repository, if someone needs to the full perspective to get everything working: https://github.com/zlepper/typescript-webworker

This repository also have a webpack.config.js to show how webpack could be configured for this.




回答3:


rasmus-hansen's solution doesn't, in its base form, allow workers to import modules themselves. After some more digging around, I found that the example in https://github.com/Qwaz/webworker-with-typescript does. I tested the version in worker-loader, and was able to trivially add a simple module than can be imported by both worker.ts and entry.ts.




回答4:


Since I migrated to file-loader": "5.0.2",

I got this issue : the worker file was returing

Uncaught SyntaxError: Unexpected token '<' and the url was /[object%20Module].

To solve it replace the workerPath in the main.ts by

import workerPath from "file-loader?name=[name].js!./search.worker";


来源:https://stackoverflow.com/questions/38715001/how-to-make-web-workers-with-typescript-and-webpack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!