2

我正在尝试为 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
});

所以在我初始化之后

using (var engine = new V8ScriptEngine())
{
  engine.Execute(@"
    const Chat = require('twilio-chat.js');

    const token = 'my token';

    Chat.Client.create(token).then(client=>{
    });
  ");
 }

'require' 行中带有错误 require 的程序错误未定义。我读过 require 只是返回模块导出,所以我替换了 require('...

engine.Execute(@"
    const Chat = ('twilio-chat.js').module.exports;
...

但是无法读取未定义的属性“出口”的错误

我从https://media.twiliocdn.com/sdk/js/chat/releases/4.0.0/twilio-chat.js获得了 js 文件

我该如何解决这个问题,或者也许有更好的方法。我感谢任何和所有的见解。

谢谢

4

1 回答 1

3

我对 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())
    );
");

这成功加载了 Twilio 脚本,该脚本似乎依赖于其他脚本和资源,这些脚本和资源不属于 ClearScript/V8 提供的裸标准 JavaScript 环境的一部分。要使其正常工作,您必须增加搜索路径并可能手动公开其他资源。如图所示,这段代码打印出来ReferenceError: setTimeout is not defined

于 2020-09-02T15:28:04.753 回答