Reputation: 6165
I'm trying to load a webpack library (that I own) using web workers in an Angular app.
To build the lib I run npm run build && npm pack
. The dist folder correctly contains 2 files:
I import the lib in the app using npm i ../lib/lib-1.0.0.tgz
. Lib & worker files are correctly imported in the app's node_modules/lib folder.
However when trying to use the lib's worker from the Angular app, I get a 404 error, as Angular does not exposes the lib's worker.
How can I do that?
Here's the code:
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();
}
}
Upvotes: 1
Views: 38
Reputation: 6165
I found a solution: just add the following to the app's angular.json (in projects
> app
> architect
> build
> assets
):
{
"glob": "*",
"input": "node_modules/lib/dist/",
"output": "/"
}
Would be better to find a way without having to update the app's config but it will do for now.
Upvotes: 1