代码之家  ›  专栏  ›  技术社区  ›  the_drow

如何在Google的V8中包含另一个JS文件?

  •  12
  • the_drow  · 技术社区  · 15 年前

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

    2 回复  |  直到 12 年前
        1
  •  22
  •   postfuturist    15 年前

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

    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");
    
        2
  •  3
  •   Petah    12 年前

    如果您使用node.js或任何与commonJS兼容的运行时,则可以使用require(module); 有一篇关于它的好文章在 http://jherdman.ca/2010-04-05/understanding-nodejs-require/