Packing required

Considering

3 Node.js projects Highlights - Framework - Repositories

The main one has two other projects connected via npm link .

In the test, I wrapped the request in a method. I have problems resolving related projects (see details below)

The simplified code is as follows:

module.export.resolve = function(file){ [...]//Some more logik to handle relative pathes return require(file) } 

This works great in most scenarios. I also worked on contacting relatives (looking at the caller and applying patterns along the way)

Now it is in the Project Structure , which is linked (npm link) to the Project Home . The main project also has Project Repositories .

Now in the main project I have:

 require('ProjectRepositories/foo') // Works as expected myRequire.resolve('ProjectRepositories/foo') // Returns MODULE_NOT_FOUND "Cannot find module 'ProjectRepositories/foo' 

I assume the problem is that the Repository Project is not related in the Framework Project . But is there any other way than linking them?

I would rather have fewer dependencies. Any hints of this?

+5
source share
1 answer

You are absolutely right that the reason the Project structure resolve does not work is because requireFn , used inside this project, knows only about the modules installed in this structure. This is because when you require a javascript file, node evaluates the script in the context of the module, not the context of the current project (this is how the dependency modules of require work if there is a script from your top level).

However, you can make a way in which the resolver Framework can use the require function requested by the user to do its job after it has changed the paths.

 module.exports.resolve = function(file, resolver) { //Some more logik to handle relative pathes resolver = typeof resolver == 'function' ? resolver : require; return resolver(file) } 

Now in your code you can do

 myRequire.resolve('ProjectRepositories/foo', require); 

So, now your main project will be used to resolve the file.

You can also do this even further if you want, and have a stateful module and remember that it must use a recognizer.

 var _requireFn = require; module.exports = { resolve: resolve, setRequireFn: setRequireFn }; function resolve(path) { return _requireFn(path); } function setRequireFn(requireFn) { _requireFn = requireFn; } 

In another note, I would be careful to use the term resolve , because in node, which is semantically used to find the correct path to the file that is required, a la require.resolve .

Finally, in terms of minimizing dependencies, I would recommend including your subprojects in npm using github repositories. This worked very well in the past, unless your two sub-posts are in a constant state. For more information, see Install Documents .

+1
source

Source: https://habr.com/ru/post/1212395/


All Articles