How do you include another js file in Google's v8?

大城市里の小女人 提交于 2019-12-03 08:21:53

问题


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?


回答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.

// 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/



来源:https://stackoverflow.com/questions/1149340/how-do-you-include-another-js-file-in-googles-v8

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!