简体   繁体   中英

Clearscript Javascript 'require' functionality

I am attempting to write a C# wrapper for the Twilio Programmable Chat tool. The library provided is for JS clients. I thought that using a tool like ClearScript (V8) would allow me to wrap the js as needed.

The example code on the site is

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
});

so after I initialize

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

    const token = 'my token';

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

The program errors on the 'require' line with the error require is not defined. I have read that require is simply returning the module exports so I replaced the require('... with

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

but that errors with Cannot read property 'exports' of undefined'

I got the js file from https://media.twiliocdn.com/sdk/js/chat/releases/4.0.0/twilio-chat.js

How can I get around this or maybe there is a better way. I appreciate any and all insights.

Thanks

I don't know anything about Twilio, but here's how to enable ClearScript's CommonJS module support. This sample loads the script from the web, but you can limit it to the local file system or provide a custom loader:

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

This successfully loads the Twilio script, which appears to be dependent on other scripts and resources that aren't part of the bare standard JavaScript environment that ClearScript/V8 provides. To get it working, you'll have to augment the search path and possibly expose additional resources manually. As shown, this code prints out ReferenceError: setTimeout is not defined .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM