Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
118 views
in Technique[技术] by (71.8m points)

How to make web workers with TypeScript and webpack

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?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...