What is proper way to access npm package in js_section of blade.php file
resources\js\app.js
import Twilio from 'twilio-video';
window.Twilio = Twilio;
also tried with:
require('twilio-video');
index.blade.php
@extends('layouts.app')
@section('content')
CONTENT...
@endsection
@section('js_section')
<script>
const {connect} = require('twilio-video');
connect('{{$result['token']}}', {name: 'test2'}).then(room => {
console.log(`Successfully joined a Room: ${room}`);
room.on('participantConnected', participant => {
console.log(`A remote Participant connected: ${participant}`);
});
}, error => {
console.error(`Unable to connect to Room: ${error.message}`);
});
</script>
@endsection
ERROR: Uncaught ReferenceError: require is not defined
require()
is not built in into the browser it is a node environment feature. So it has no access from a blade template. What can you do is to compile another js file in your webpack.mix.js
and pass token into from a hidden input.
Write your code in custom.js
const {connect} = require('twilio-video');
// it will contain $result['token']
const roomToken = document.querySelector('.room-token').value;
connect(roomToken, {name: 'test2'}).then(room => {
console.log(`Successfully joined a Room: ${room}`);
room.on('participantConnected', participant => {
console.log(`A remote Participant connected: ${participant}`);
});
}, error => {
console.error(`Unable to connect to Room: ${error.message}`);
});
Add it in webpack.mix.js and compile (with npm run dev
for example - depends on your package.json
scripts and environment)
let mix = require('laravel-mix');
mix.js('path/to/custom.js', 'public/folder');
and in your blade.php
@section('js_section')
<input type="hidden" class="room-token" value="{{ $result['token'] }}" />
<script src="{{ asset( 'path/to/complied/custom.js' ) }}"></script>
@endsection