如何使用 TypeScript 和 webpack 打造网络工作者 [英] How to make web workers with TypeScript and webpack

查看:34
本文介绍了如何使用 TypeScript 和 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]);
    }
};

在我的应用程序的另一部分,我使用 webpack worker loader 像这样加载我的 worker:let Worker = require('worker!../../../workers/uploader/main');

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

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

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"
          ]
     }
}

现在,当我运行 webpack 让它构建所有东西时,我得到了一堆这样的错误:C:/Users/hanse/Documents/Frontend/node_modules/typescript/lib/lib.webworker.d.ts:1195:13后续变量声明必须具有相同的类型.变量 'navigator' 必须是 'Navigator' 类型,但这里的类型是 'WorkerNavigator'.

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

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

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?

推荐答案

在你的 tsconfig.json 文件中,在 compilerOptions 中设置:

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 Worker 无法访问 DOM、windowdocumentparent 对象(此处支持的完整对象列表:Web Workers 可用的函数和类);TypeScript 的 dom 库不兼容,重新定义了一些在 lib.webworker.d.ts

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

这篇关于如何使用 TypeScript 和 webpack 打造网络工作者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆