Quantcast
Channel: ClearScript
Viewing all articles
Browse latest Browse all 2297

Commented Unassigned: Support a CommonJS environment for V8 [45]

0
0
To my understanding, ClearScript V8 does not support the [CommonJS](http://stackoverflow.com/questions/16521471/relation-between-commonjs-amd-and-requirejs) standard ([official website](http://www.commonjs.org/)).

My suggestion is to support this.

Alternatively, as you [suggested here](https://clearscript.codeplex.com/workitem/31#PostedByLink1) for the `window` object, is there a way for myself to support the CommonJS API/standard by adding some script and/or host objects?

_(My ultimative goal is to use some 3rd party NodeJS modules inside ClearScript V8 without having to modify their source code to work with ClearScript)_
Comments: Hi UweKeim, Here's a barebones XMLHttpRequest mockup that works with CommonScript: ``` C# public class CommonScriptXMLHttpRequest { private string _url; private readonly ListDictionary _listeners = new ListDictionary(); public string responseText { get; private set; } public void open(string method, string url, bool async) { _url = url; } public void setRequestHeader(string name, string value) { } public void addEventListener(string name, object listener, bool capture) { _listeners[name.ToLower()] = listener; } public void send(object body = null) { responseText = getScriptModule(new Uri(_url).AbsolutePath); notify(); } public int status { get { return (responseText != null) ? 200 : 404; } } public string statusText { get { return (responseText != null) ? "200 OK" : "404 Not Found"; } } private void notify() { var name = (responseText != null) ? "load" : "error"; if (_listeners[name] != null) ((dynamic)_listeners[name])(); } private static string getScriptModule(string path) { // TODO: replace with your implementation if (path == "/console.js") return "exports.log = Console.WriteLine"; return string.Format("require('console').log('module {0}')", path); } } ``` And here's how you could use it with ClearScript: ``` C# // set up script environment engine.AddHostType("Console", typeof(Console)); engine.AddHostType("XMLHttpRequest", typeof(CommonScriptXMLHttpRequest)); engine.Script.location = new { protocol = "http:", host = "localhost", pathname = string.Empty }; // run CommonScript modules.js using (var client = new WebClient()) engine.Execute(client.DownloadString("https://raw.githubusercontent.com/Localnet/CommonScript/master/lib/modules.js")); // we now have CommonJS Modules/1.1.1 engine.Execute("require('foo')"); ``` Obviously in your real-world scenario you probably wouldn't want to download modules.js from GitHub every time :) Is something like this practical for you? If so, please let us know and we'll close this issue. Thanks!

Viewing all articles
Browse latest Browse all 2297