Clearscript Javascript“需要”功能

问题描述

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

但是出现错误,无法读取未定义的属性“ 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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...