JInt需要另一个JS文件。

4
我想找到一种在JInt(C# Unity的JavaScript解释器)中本地包含另一个js文件的方法。我知道可以将所有js文件简单地连接成一个字符串,并通过正常方式运行它。但我不想指定要加载的确切文件和文件加载顺序。我有未定义数量的文件在文件夹和子文件夹中,我只知道哪个文件是main.js。
是否有可能使用类似于nodejs的require('file.js'),或者这是一个完全不好的想法?
谢谢。
附言:此项目旨在在Unity-JInt下运行。
1个回答

5

我不确定jint是否提供此功能。但你可以尝试类似以下的方法:

假设你有如下两个js文件。

// file1.js
log('Hiii.. I am file 1');
require('C:\\file2.js');

// file2.js
log('Hiii.. I am file 2');

你可以按照以下方式构建require
using System;
using Jint;
using Jint.Native;

namespace JintSample
{
    class Program
    {
        static void Main(string[] args)
        {
            var engine = new Engine();
            JsValue require(string fileName)
            {
                string jsSource = System.IO.File.ReadAllText(fileName);
                var res = engine.Execute(jsSource).GetCompletionValue();
                return res;
            }

            engine.SetValue("require", new Func<string, JsValue>(require))
            .SetValue("log", new Action<string>(System.Console.WriteLine));

            JsValue name = engine.Execute(@"require('C:\\file1.js')").GetCompletionValue();
        }
    }
}

我希望这能对你有所帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接