首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Clearscript Javascript 'require‘功能

Clearscript Javascript 'require‘功能
EN

Stack Overflow用户
提问于 2020-09-02 06:53:04
回答 1查看 567关注 0票数 2

我正在尝试为Twilio可编程聊天工具编写一个C#包装器。提供的库是为JS客户端提供的。我认为使用像ClearScript (V8)这样的工具可以让我根据需要包装js。

该站点上的示例代码为

代码语言:javascript
复制
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
});

所以在我初始化之后

代码语言:javascript
复制
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('...使用

代码语言:javascript
复制
engine.Execute(@"
    const Chat = ('twilio-chat.js').module.exports;
...

但是该错误不能读取属性'exports‘of undefined’

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

我如何才能绕过这个问题,或者也许有更好的方法。我很欣赏任何和所有的见解。

谢谢

EN

回答 1

Stack Overflow用户

发布于 2020-09-02 23:28:05

我对Twilio一无所知,但这里介绍了如何启用ClearScript的CommonJS模块支持。此示例从web加载脚本,但您可以将其限制为本地文件系统或提供自定义加载程序:

代码语言:javascript
复制
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())
    );
");

要使其正常工作,您必须增加搜索路径,并可能手动公开额外的资源。如图所示,此代码输出ReferenceError: setTimeout is not defined

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63696472

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档