如何使用 TypeScript 和 webpack 打造网络工作者

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38715001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:15:38  来源:igfitidea点击:

How to make web workers with TypeScript and webpack

typescriptwebpackweb-worker

提问by Rasmus Hansen

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');

在我的应用程序的另一部分,我使用 webpack worker loader 像这样加载我的 worker: 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:

但是,当必须转换应用程序时,我在使打字稿声明不会对我大喊大叫时遇到了一些问题。根据我的研究,我必须在我的 tsconfig 文件中添加另一个标准库,以公开工作人员需要访问的全局变量。这些我已经指定如下:

{
     "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'.

现在,当我运行 webpack 让它构建所有东西时,我得到了一堆这样的错误: 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?

所以我的问题是:如何指定以便 webworker 使用 lib.webworker.d.ts 定义而其他所有内容都遵循正常定义?

采纳答案by batressc

In your tsconfig.jsonfile, in compilerOptionsset this:

在您的tsconfig.json文件中,compilerOptions设置如下:

{
    "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, documentand parentobjects (full list supported objects here: Functions and classes available to Web Workers); the domlib of TypeScript is not compatible and redefine some elements that are define in lib.webworker.d.ts

网站工作人员不能访问DOM, windowdocumentparent对象(名单支持此对象:可使用的功能和类网络工作者); domTypeScript的lib 不兼容,重新定义了一些在lib.webworker.d.ts

回答by Rasmus Hansen

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

使用 batressc 的回答,我已经设法以一种有点不错的方式来回传递消息。

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

除了他对库的回答之外,Typescript 代码还需要一些推动才能开始工作。

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

首先创建一个文件,让file-loader在导入时配合你。我有一个以file-loader.d.ts以下内容命名的文件:

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

Next, in your main.tsimport the worker using the fileloader:

接下来,在main.ts使用文件加载器导入工作器时:

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

This workerPathcan then be used to create the actual worker:

workerPath可以被用来创建实际工作者:

const worker = new Worker(workerPath);

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

接下来,创建test.worker.ts具有以下内容的实际工作文件:

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.tsfile:

然后,您可以在main.ts文件中来回发送消息:

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

我已经在 github 存储库中收集了所有内容,如果有人需要完整的视角才能使一切正常工作:https: //github.com/zlepper/typescript-webworker

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

这个存储库也有一个webpack.config.js展示如何为此配置 webpack。

回答by lutzky

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-typescriptdoes. I tested the version in worker-loader, and was able to trivially add a simple module than can be imported by both worker.tsand entry.ts.

rasmus-hansen 的解决方案在其基本形式中不允许工作人员自己导入模块。经过更多的挖掘,我发现https://github.com/Qwaz/webworker-with-typescript中的示例确实如此。我测试的版本worker-loader,并能够添加平凡简单的模块比可由两个进口worker.tsentry.ts

回答by Pouya

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

自从我移民到file-loader": "5.0.2"

I got this issue : the worker file was returing

我遇到了这个问题:工作文件正在返回

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

Uncaught SyntaxError: Unexpected token '<'网址是/[object%20Module].

To solve it replace the workerPath in the main.tsby

为了解决这个问题更换workerPath在main.ts通过

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