how to remove parcelRequire is not defined with peerjs in ionic

Viewed 1829

i am building a video chat application with ionic 5, i dont know how to properly use it, i tried but i keep getting this error in the console

Uncaught ReferenceError: parcelRequire is not defined
    at push../node_modules/peerjs/dist/peerjs.min.js.parcelRequire.EgBh (peerjs.min.js:1)
    at Object../node_modules/peerjs/dist/peerjs.min.js

Here is my code

import { Injectable } from '@angular/core';
import Peer from 'peerjs';

@Injectable({
    providedIn: 'root' 
}) 
export class WebrtcService {
    peer: Peer;
    myStream: MediaStream;
    myEl: HTMLMediaElement;
    partnerEl: HTMLMediaElement;
    options:any= {
        host: 'localhost',
        port: 9000,
        path: '/peerjs',
        debug: 3,
        config: {
            'iceServers': [{
                    url: 'stun:stun1.l.google.com:19302'
                },{
                    url: 'turn:numb.viagenie.ca',
                    credential: 'muazkh',
                    username: 'webrtc@live.com'
                }
            ]
        }
    }
    constructor() {}

    getMedia() {
        navigator.getUserMedia({ audio: true, video: true },stream=>this.handleSuccess(stream),
        (error) =>this.handleError(error));
    }

    async init(userId: string, myEl: HTMLMediaElement, partnerEl: HTMLMediaElement) {
        this.myEl = myEl;
        this.partnerEl = partnerEl;
        try {
            this.getMedia();
        } catch (e) {
            this.handleError(e);
        }
        await this.createPeer(userId);
    }

    async createPeer(userId: string) {
        this.peer = new Peer(userId, this.options);
        this.peer.on('open', ()=>this.wait())
    }

    call(partnerId: string) {
        const call = this.peer.call(partnerId, this.myStream);
        call.on('stream', (stream)=>this.partnerEl.srcObject = stream);
    }

    wait() {
        this.peer.on('call', (call) => {
            call.answer(this.myStream);
            call.on('stream', (stream) =>this.partnerEl.srcObject = stream);
        });
    }

icomment most of the code to find out where the error is coming from, i noticed that the error happens when this.peer = new Peer(userId, this.options); is being runned.

Also i noticed that if i should run this in other pages it will work, but if it is being run in a app.component.ts, it will give me that error, i seriously need the above code to be in app.component.ts

3 Answers

Try this:

<script>
    var parcelRequire;
</script>

(From here.)

It is solved in parcel version 2, simply install parcel

npm i -D parcel

If your script uses type="module" - remove it.

Related