How do you include another script file inside a .js script file in v8?
There's the <script> tag in HTML but how can it be done inside a v8 embedded program?
如何在v8中的.js脚本文件中包含另一个脚本文件? HTML中有
2 个解决方案
#1
You have to add this functionality manually, here is how I did it:
您必须手动添加此功能,以下是我的操作方法:
Handle<Value> Include(const Arguments& args) {
for (int i = 0; i < args.Length(); i++) {
String::Utf8Value str(args[i]);
// load_file loads the file with this name into a string,
// I imagine you can write a function to do this :)
std::string js_file = load_file(*str);
if(js_file.length() > 0) {
Handle<String> source = String::New(js_file.c_str());
Handle<Script> script = Script::Compile(source);
return script->Run();
}
}
return Undefined();
}
Handle<ObjectTemplate> global = ObjectTemplate::New();
global->Set(String::New("include"), FunctionTemplate::New(Include));
It basically adds a globally accessible function that can load and run a javascript file within the current context. I use it with my project, works like a dream.
它基本上添加了一个全局可访问的函数,可以在当前上下文中加载和运行javascript文件。我在我的项目中使用它,就像一个梦想。
// beginning of main javascript file
include("otherlib.js");
#2
If you're using Node.js or any CommonsJS compliant runtime, you can use require(module); There's a nice article about it at http://jherdman.ca/2010-04-05/understanding-nodejs-require/
如果您正在使用Node.js或任何符合CommonsJS的运行时,您可以使用require(module);在http://jherdman.ca/2010-04-05/understanding-nodejs-require/上有一篇很好的文章
#1
You have to add this functionality manually, here is how I did it:
您必须手动添加此功能,以下是我的操作方法:
Handle<Value> Include(const Arguments& args) {
for (int i = 0; i < args.Length(); i++) {
String::Utf8Value str(args[i]);
// load_file loads the file with this name into a string,
// I imagine you can write a function to do this :)
std::string js_file = load_file(*str);
if(js_file.length() > 0) {
Handle<String> source = String::New(js_file.c_str());
Handle<Script> script = Script::Compile(source);
return script->Run();
}
}
return Undefined();
}
Handle<ObjectTemplate> global = ObjectTemplate::New();
global->Set(String::New("include"), FunctionTemplate::New(Include));
It basically adds a globally accessible function that can load and run a javascript file within the current context. I use it with my project, works like a dream.
它基本上添加了一个全局可访问的函数,可以在当前上下文中加载和运行javascript文件。我在我的项目中使用它,就像一个梦想。
// beginning of main javascript file
include("otherlib.js");
#2
If you're using Node.js or any CommonsJS compliant runtime, you can use require(module); There's a nice article about it at http://jherdman.ca/2010-04-05/understanding-nodejs-require/
如果您正在使用Node.js或任何符合CommonsJS的运行时,您可以使用require(module);在http://jherdman.ca/2010-04-05/understanding-nodejs-require/上有一篇很好的文章