简体   繁体   English

我如何在npm中要求()网络工作者?

[英]How do I require() web workers in npm?

I've got a npm/webpack setup, and part of my application requires Web Workers. 我有一个npm / webpack设置,我的部分应用程序需要Web Workers。 Normally, web workers are created with this syntax: 通常,使用以下语法创建Web worker:

var worker = new Worker('path/to/external/js/file.js');

In npm, this doesn't work, because the development environment I'm using doesn't accept paths like this. 在npm中,这不起作用,因为我正在使用的开发环境不接受这样的路径。 Files must be included using require() . 必须使用require()包含文件。

I can't just link to the file absolutely, since that violates the cross-origin rule thing. 我不能绝对链接到该文件,因为这违反了跨源规则的事情。

Is there a strategy for including these worker files? 是否有包含这些工作文件的策略?

The worker-loader loader provided by Webpack seems to provide a solution to your problem. Webpack提供的worker-loader loader似乎为您的问题提供了解决方案。 This module can be installed with npm install --save-dev worker-loader . 该模块可以使用npm install --save-dev worker-loader

Take a look at how to use loaders , then require your web worker files like so: 看一下如何使用加载器 ,然后需要你的web worker文件:

const Foo = require("worker!./path/to/external/js/file.js");
const fooWorker = new Foo();

Note the worker! 注意worker! prepended before the path, which tells Webpack to use the worker loader specifically. 在路径之前预先设置,告诉Webpack专门使用工作负载。

You should be able to require modules normally in the worker file itself also, provided your setup is correct. 如果您的设置正确,您应该能够在工作文件本身中正常需要模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM