Compiling multiple js files into one context

165 views
Skip to first unread message

Gautham B A

unread,
Oct 16, 2017, 2:29:37 AM10/16/17
to v8-users
Hi all,

I was wondering if it's possible to compile multiple javascript source files into a single context. For example,
// File a.js
function f1(){
    console
.log(10);
}

// File b.js
function f2(){
    console
.log(20);
}

In C++, I'm trying to compile them one after another -
//Sources v8 string
v8
::String a_js = ...
v8
::String b_js = ...

// Compiling them one after another
v8
::Script::Compile(context, a_js);
auto script = v8::Script::Compile(context, b_js).ToLocalChecked();

Now, when I try to grab the reference to f1 (function in a.js) in the C++ function, I get an empty handle, I assume that when I compiled b.js, the context got overwritten.
Could anyone please tell me if it's possible to compile multiple sources into the same context?

Thanks,
--Gautham

Zac Hansen

unread,
Oct 16, 2017, 6:48:52 AM10/16/17
to v8-users
it's always best to post the full code to reproduce your issue.

Brandon Jonson

unread,
Oct 16, 2017, 9:32:14 AM10/16/17
to v8-users
Yes you can. As per Zac's suggestion it looks like you're missing some vital pieces here. For one, you should give each loaded script a name. If an error occurs it'll give you the name of the script the error occurred in along with the line number of THAT script. Also, you should run the script after each compile. I'd also add a TryCatch in case something went wrong. Otherwise if this isn't what you need you could also concatenate the script in your program elsewhere and load it once. If you are using multiple contexts within the same isolate just be sure you have the correct context scope for the one you're loading. 

(This will be my first time writing a code block in this forum so hopefully it comes out right).

//Assume you did all the necessary setup like isolate scope, handle scope, context scope, locker already...

Local<String> nameOfScript = String::NewFromUtf8(isolate, "a.js");
Local<String> sourceOfScript = String::NewFromUtf8(isolate, "<code of a.js>");

ScriptOrigin origin(nameOfScript); //<- for the name of script being compiled
Local<Script> script = Script::Compile(sourceOfScript, &origin);

Handle<Value> result = script->Run();

//Now do the same as above for script b.js

//NOTE: I'd add a TryCatch in here too in case something went wrong in the compile/load/run of each script.  
Reply all
Reply to author
Forward
0 new messages