Evaluate a module in another modular context

I know this is very bad. (I am writing a library, and I would like my require library method to work exactly the same in the browser and on NodeJS.)

I want this to be possible, this is to evaluate the script in the context of the current module, that is, if I say exports.a = "100"; in the module, I would like for exports.a be equal to "100" in all the code in the require module after require .

If this is not clear, I would be happy to develop.

+4
source share
2 answers

This will not be the full answer, but I hope it helps you in the right direction.

I have already been busy with Node's module building system in the last couple of days. Basically, I wanted to create several modules that were called in a completely new context and variable field, for which I would define a limited subset and extension of Node's capabilities.

I ended up exploring their source here and focused on the NativeModule constructor and its methods.

You will notice that the module source is read from the file, wrapped in a string representing the function, and eval'd in the actual code.

Wrapper:

 NativeModule.wrapper = [ '(function (exports, require, module, __filename, __dirname, define) { ', '\n});' ]; 

A function is called that calls the contained module code.

A function requires half a dozen arguments, as you can see from the wrapper, the first of which is the exports object (which starts from empty). It is also passed in to the require function, so you can access require as a variable, although require not global.

The module code populates the exports object, and then exports cached, so everything that works does not need to be done in the future. Therefore, when require( 'someModule' ) , it simply scans the cached exports object and returns it.

I am sure that you could do something similar in your code while you can get the source for the required module.

Maybe for you there will be SomeModule.toString() . Not sure how compatible browser support is.


There is also a private API that is used to configure the environment for modules.

 process.binding('evals').Script /* { [Function: Script] createContext: [Function], runInContext: [Function], runInThisContext: [Function], runInNewContext: [Function] } */ 

I had to use createContext and runInContext to get everything working, but I think you probably won't need anything.

+1
source

(I am writing a library, and I need my library method to work exactly the same in a browser and on NodeJS

If I understand you correctly (please forgive me if not;)), you are looking for something like node-browserify .

Browserify require () browser for your node modules and npm packages

Just specify a javascript file or two for the browser and it will be AST to read all your require () s recursively. The resulting bundle has everything you need, including pulling out libraries that you can install using npm!

0
source

All Articles