15

如何在 v8 中的 .js 脚本文件中包含另一个脚本文件?
HTML 中有 <script> 标签,但如何在 v8 嵌入式程序中完成呢?

4

2 回答 2

25

您必须手动添加此功能,我是这样做的:

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

它基本上添加了一个全局可访问的函数,可以在当前上下文中加载和运行 javascript 文件。我在我的项目中使用它,就像做梦一样。

// beginning of main javascript file
include("otherlib.js");
于 2009-08-23T06:34:10.030 回答
3

如果您使用的是 Node.js 或任何符合 CommonsJS 的运行时,您可以使用 require(module); 在http://jherdman.ca/2010-04-05/understanding-nodejs-require/上有一篇关于它的好文章

于 2010-11-24T19:48:18.270 回答