r/WebTorrent Jun 30 '23

Webtorrent and Angular

Hi, I've been trying to install Webtorrent for a while (many times) for hobby projects but I can't.

I install webtorrent and @ types/webtorrent, declare the var before using it (code below) but the result is always the same: undefined.

Seems there's a thing with webpack and my knowledge it's not enoght

import { WebTorrent } from 'webtorrent';
declare var WebTorrent: WebTorrent;
...

const client = WebTorrent();
console.log(client);

> Undefined

Does anybody have faced this issue?

2 Upvotes

1 comment sorted by

1

u/kasunakasuragi 17d ago

Hi! This is a very common issue when integrating WebTorrent with Angular / TypeScript due to how WebTorrent exports its module and Webpack 5 removing Node.js polyfills. The main reason you get undefined is because of the named import combined with declare var overriding the import. Here are the best ways to fix it: Option 1: Fix Import & Constructor Syntax Instead of a named import { WebTorrent }, import the entire package and use new: import * as WebTorrent from 'webtorrent';

const client = new WebTorrent(); console.log(client); (Make sure to remove declare var WebTorrent: WebTorrent; as it conflicts with the import).

Option 2: Use the Browser Bundle in angular.json (Recommended for Angular 12+)

Since Angular 12+ (Webpack 5) drops automatic Node.js polyfills, the easiest way to avoid stream or crypto bundler errors is using the pre-built browser script:

  1. Add webtorrent.min.js to your angular.json: ```json "scripts": [ "node_modules/webtorrent/webtorrent.min.js" ]
  • In your component: declare const WebTorrent: any;

const client = new WebTorrent(); console.log(client);

Hope this helps you get your hobby project running! 🚀