JInt require another js file
Asked Answered
C

1

5

I am looking a way to include another js file natively in JInt (javascript interpreter for C# Unity). I understand that I can simple concatenate all my js files to one string and run it via normal way. But I don't want to specify exact files to load and also file loading order. I have undefined amount of files in the folder and subfolders and I only know which file is main.js.

It there a possibility to use something like require('file.js') from nodejs or it's a completely bad idea?

Thank you.

P.S. This project intended to be run under Unity-JInt.

Citrange answered 14/2, 2018 at 19:22 Comment(0)
M
6

I am not sure whether jint provides such functionality. But you can try something like

Let's say you have two js files as shown below.

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

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

you can build require as shown below.

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

I hope this helps you.

Mantis answered 25/2, 2018 at 10:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.