从 Angular 项目中的 webpack 库导入worker

问题描述 投票:0回答:1

我正在尝试在 Angular 应用程序中使用 Web Worker 加载 Webpack 库(我拥有的)。

为了构建库,我运行

npm run build && npm pack
。 dist 文件夹正确包含 2 个文件:

  • lib.js:库代码
  • 408.lib.js:工作代码

我使用

npm i ../lib/lib-1.0.0.tgz
在应用程序中导入库。 Lib 和worker 文件已正确导入到应用程序的node_modules/lib 文件夹中。

但是,当尝试从 Angular 应用程序使用库的工作程序时,我收到 404 错误,因为 Angular 不会公开库的工作程序。

我怎样才能做到这一点?

这是代码:

lib/webpack.config.js:

const Path = require('path');

module.exports = {
    entry: './src/index.js',
    output: {
        path: Path.resolve(__dirname, 'dist'),
        filename: 'lib.js',
        globalObject: 'this',
        library: {
            name: 'webpackNumbers',
            type: 'umd'
        },
    }
};

lib/package.json:

{
  "name": "lib",
  "version": "1.0.0",
  "description": "",
  "private": true,
  "main": "dist/lib.js",
  "scripts": {
    "build": "webpack --mode production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^5.91.0",
    "webpack-cli": "^5.1.4"
  }
}

lib/src/index.js:

const worker = new Worker(new URL('./worker.js', import.meta.url));

export function testWorker() {

    worker.postMessage({
        question: 'The Answer to the Ultimate Question of Life, The Universe, and Everything.',
    });
    worker.onmessage = ({ data: { answer } }) => {
        console.log(answer);
    };
}

lib/src/worker.js:

self.onmessage = ({ data: { question } }) => {
    self.postMessage({
        answer: 42,
    });
};

app/src/app/app.component.ts:

import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import * as lib from 'lib';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent {
  title = 'app';

  constructor() {
    lib.testWorker();
  }
}
angular webpack web-worker
1个回答
0
投票

好吧,刚刚找到解决方案。我只需要将以下内容添加到应用程序的 angular.json 中的项目 > 应用程序 > 架构师 > 构建 > 资产部分:

{
  "glob": "*",
  "input": "node_modules/lib/dist/",
  "output": "/"
}
© www.soinside.com 2019 - 2024. All rights reserved.