C#.Net ClearsScript V8启用模块

时间:2019-05-15 13:08:49

标签: c# .net v8 clearscript

是否有启用“ import .js;”的方法?嵌入式V8运行时中使用Microsoft ClearScript的语句?

我找不到任何示例,让我觉得我必须自己先解析脚本文件才能启用此功能。

2 个答案:

答案 0 :(得分:0)

是的。基本方法请参见answer to this question。这个问题与启用CommonJS Require有关。对于ES6模块方法,您将需要以下内容:

using System;
using Microsoft.ClearScript;
using Microsoft.ClearScript.JavaScript;
using Microsoft.ClearScript.V8;

namespace ConsoleApp1
{
    class Program
    {
        static void Main()
        {
            V8ScriptEngine engine = new V8ScriptEngine();
            engine.DocumentSettings.SearchPath = @"c:\temp\js\";
            engine.DocumentSettings.AccessFlags = DocumentAccessFlags.EnableFileLoading;
            engine.AddHostType(typeof(Console));
            Console.WriteLine("Hello from C#");
            engine.Execute(new DocumentInfo() { Category = ModuleCategory.Standard }, @"
                Console.WriteLine('Hello from Javascript');
                import {print} from 'a.js';
                import {add} from 'b.js';
                print(add(30, 12));
                Console.WriteLine('Javascript signing off...');
            ");
            Console.ReadKey();
        }
    }
}

JS如下所示:

// File c:\temp\js\a.js
export function print(txt) {
    Console.WriteLine('The answer to Life etc is ... ' + txt);
  }

// File c:\temp\js\b.js 
export function add(var1, var2) {
    return var1 + var2;
  } 

结果是:

Output of sample code

此示例从AccessFlags = EnableFileLoading设置指示的本地文件系统中读取文件,其中SearchPath设置提供路径,或者如果给出以逗号分隔的路径列表,则提供路径。

“ ModuleCategory.Standard”选项可启用ES6样式的模块加载。

答案 1 :(得分:0)

您也可以使用类似于 node.js 的自行滚动的 require() 函数。我写了一篇博客文章 here 并且有一个 working CodePen 来说明这种方法,该方法受到 article by Michele Nasti 的启发,chapter 10 本身基于 Eloquent JavaScript 书中的想法{{ 3}} 作者:Marijn Haverbeke。

这是我的编码示例:

const myCode1 = `
  let utils = function (){
    this.say = function(x){
      log('utils: says = ' + x)
      };
      return this;
  }
  exports.utils = utils;
`;
const myCode2 = `
  let customer = function (){
    this.say = function(x){
      log('Customer: says = ' + x)
      };
      return this;
  }
  exports.customer = customer;
`;
/*

*/  
// I am loading simple source code strings into an array - in the real solution
// you would use some kind of source code fetch / load to string process.
let sourceCode = {c1: myCode1, c2: myCode2};
myRequire.cache = Object.create(null); 

function myRequire(name) {   
    log(`myRequire: You require file ${name}`)
    if (!(name in myRequire.cache)) {
        log(`myRequire: ${name} is not in cache; reading from disk`)
        let code = sourceCode[name]; // load the code - this is bespoke to your env      
        let module = {exports: {}};
        myRequire.cache[name] = module;     
        let wrapper = Function("require, exports, module", code);     
        wrapper(myRequire, module.exports, module);
    }
    log(`myRequire: ${name} is in cache. Returning it...`)
    return myRequire.cache[name].exports;
}

// myRequire() produces an object from the 'exports' object in the loaded code.
//let myExports = new myRequire('c1');
// we can then refer to these as 
// let util = myExports.utils();
// or just use 
// let util = new myRequire('c1').utils();

// So...Require c1 will create an object with exports.
let util = new myRequire('c1').utils();
util.say('I am alive!')
 
log("");

// Require c2 will create an object with exports.
let cust = new myRequire('c2').customer();
cust.say('I am alive too!')

function log(msg){
  $('#log').html($('#log').html() + "<br />" + msg);
}

输出是

myRequire: You require file c1
myRequire: c1 is not in cache; reading from disk
myRequire: c1 is in cache. Returning it...
utils: says = I am alive!

myRequire: You require file c2
myRequire: c2 is not in cache; reading from disk
myRequire: c2 is in cache. Returning it...
Customer: says = I am alive too!