Laravel 在 .blade.php js 中访问 npm 包

Laravel Access npm packages in .blade.php js

在 blade.php 文件 js_section 中访问 npm 包的正确方法是什么

resources\js\app.js

import Twilio from 'twilio-video';
window.Twilio = Twilio;

也试过:

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

错误: 未捕获的引用错误:未定义要求

require 和 import 是 Laravel-mix(webpack)

的命令

您有 运行 Laravel-mix 用于从资源到包(准备好的文件)的构建结果。

运行 在终端

npm install
npm i twilio-video
npm run dev

require() 没有内置到浏览器中,它是节点环境功能。因此它无法从 blade 模板进行访问。你能做的是在你的 webpack.mix.js 中编译另一个 js 文件并从隐藏的输入中传递令牌。

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}`);
});

将其添加到 webpack.mix.js 并编译(例如使用 npm run dev - 取决于您的 package.json 脚本和环境)

let mix = require('laravel-mix');

mix.js('path/to/custom.js', 'public/folder');

在你的blade.php

@section('js_section')
    <input type="hidden" class="room-token" value="{{ $result['token'] }}" />
    <script src="{{ asset( 'path/to/complied/custom.js' ) }}"></script>
@endsection