在blade.php文件的js_section中访问npm包的正确方法是什么
资源\js pp.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()
未内置于浏览器中,它是一个节点环境功能。因此它无法从刀片模板进行访问。你能做的就是在你的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
Require 和 import 是 Laravel-mix(webpack) 的命令
您已经运行 Laravel-mix 来获取从资源到捆绑包(准备好的文件)的构建结果。
在终端中运行
npm install
npm i twilio-video
npm run dev