问题描述
我正在尝试为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文件
谢谢
解决方法
我对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
。