Well, it works pretty similar to what node.js does, so lets have a look at that:
https://github.com/nodejs/node/blob/master/lib/internal/bootstrap_node.js
Starting with line 386 a minimal module system is implemented.
The interesting part is the compile function in line 473. The given source is basically spliced into a function declaration (pretty much as you suggested) to ensure that everything is local to the function end not in the global context. Note how there is no line break after the header. This is done so that line numbers of errors encountered will still be correct after the splicing. However, any errors in the first line of source will be very strange to the user.
The next step is to run the resulting function declaration through the engine. In my case I have defined the runInThisContext function as follows in c#:
What I would like to do now is wrap source like this:
And then tell the engine to offset all line positionsi n error messages by -1. Then errors in the first line of source could produce good error messages as well.
https://github.com/nodejs/node/blob/master/lib/internal/bootstrap_node.js
Starting with line 386 a minimal module system is implemented.
The interesting part is the compile function in line 473. The given source is basically spliced into a function declaration (pretty much as you suggested) to ensure that everything is local to the function end not in the global context. Note how there is no line break after the header. This is done so that line numbers of errors encountered will still be correct after the splicing. However, any errors in the first line of source will be very strange to the user.
The next step is to run the resulting function declaration through the engine. In my case I have defined the runInThisContext function as follows in c#:
privateobject RunInThisContext( string source, dynamic settings ) { string filename = _GetFileName(settings); var moduleLoader = Engine.Evaluate( filename, false, source ); return moduleLoader; }
'(function (exports, require, module, __filename, __dirname) {\n', + source + '\n});'