Jef*_*eff 4 c# clearscript twilio-programmable-chat
我正在尝试为 Twilio 可编程聊天工具编写 C# 包装器。提供的库适用于 JS 客户端。我认为使用像 ClearScript (V8) 这样的工具可以让我根据需要包装 js。
网站上的示例代码是
const Chat = require('twilio-chat');
// Make a secure request to your backend to retrieve an access token.
// Use an authentication mechanism to prevent token exposure to 3rd parties.
const accessToken = '<your accessToken>';
Chat.Client.create(accessToken)
.then(client => {
// Use Programmable Chat client
});
Run Code Online (Sandbox Code Playgroud)
所以在我初始化之后
using (var engine = new V8ScriptEngine())
{
engine.Execute(@"
const Chat = require('twilio-chat.js');
const token = 'my token';
Chat.Client.create(token).then(client=>{
});
");
}
Run Code Online (Sandbox Code Playgroud)
“require”行上的程序错误,错误要求未定义。我读过 require 只是返回模块导出,所以我将 require('... 替换为
engine.Execute(@"
const Chat = ('twilio-chat.js').module.exports;
...
Run Code Online (Sandbox Code Playgroud)
但出现 Cannot read property 'exports' of undefined' 错误
我从https://media.twiliocdn.com/sdk/js/chat/releases/4.0.0/twilio-chat.js获取了js文件
我该如何解决这个问题,或者也许有更好的方法。我很欣赏任何和所有的见解。
谢谢
我对 Twilio 一无所知,但以下是如何启用 ClearScript 的 CommonJS 模块支持。此示例从 Web 加载脚本,但您可以将其限制为本地文件系统或提供自定义加载程序:
engine.AddHostType(typeof(Console));
engine.DocumentSettings.AccessFlags = DocumentAccessFlags.EnableWebLoading;
engine.DocumentSettings.SearchPath = "https://media.twiliocdn.com/sdk/js/chat/releases/4.0.0/";
engine.Execute(new DocumentInfo() { Category = ModuleCategory.CommonJS }, @"
const Chat = require('twilio-chat');
const token = 'my token';
Chat.Client.create(token).then(
client => Console.WriteLine(client.toString()),
error => Console.WriteLine(error.toString())
);
");
Run Code Online (Sandbox Code Playgroud)
这成功加载了 Twilio 脚本,该脚本似乎依赖于不属于 ClearScript/V8 提供的裸标准 JavaScript 环境的其他脚本和资源。要使其正常工作,您必须增加搜索路径,并可能手动公开其他资源。如图所示,此代码打印出ReferenceError: setTimeout is not defined
.