How to include a JavaScript file in another JavaSc

2019-07-07 12:13发布

问题:

This question already has an answer here:

  • How to reference a JScript file from another one? 3 answers

I know that many similar questions have been asked before. The difference in my case is that I am using Windows Scripting Host and am running the script from the DOS command line, not from inside a browser.

The only way I can think of doing this is to read the file from the disk as text using fso.OpenTextFile(ThisFile, 1), and then using the eval function to treat the text as code.

Is there a more convenient way?

回答1:

As far as I can tell, no, that's the only real option. Example:

text.js:

var fso = new ActiveXObject("Scripting.FileSystemObject");
var ts = fso.OpenTextFile("foo.js");
var script = ts.ReadAll();
eval(script);
foo();
WScript.Echo(bar);

foo.js:

var bar = "testing";
function foo() {
    WScript.Echo("foo");
}

Output:

foo
testing