How can I use modules with templates in transit?

How to include all files in nodeJS e.g.

require('./packages/city/model/cities') require('./packages/state/model/states') require('./packages/country/model/countries') 

as

 require('./packages/*/model/*') 

the same as grunt is file upload.

+6
source share
3 answers

You cannot (or at least should not)

To do this, you will have to overload the node native require function, which is extremely impractical.

The CommonJS template may seem tedious to you, but it is very good, and you should not try to break it just because you saw shortcuts in other languages ​​/ frames.

By introducing some kind of magic into your module, you suddenly change everything that programmers can (and should be able to) safely assume about the CommonJS template itself.

+4
source

Due to the one-to-one correspondence in the node module loading system, it will not be possible initially, but will not be surprised if there is a package for this method.

Best of all, you can create index.js which loads the modules present in the directory and exports them as your own.

 module.exports = function() { return { city : require('./city/model/'), state : require('./packages/state/model/'), country : require('./packages/country/model/') } } 

You will have to load models in the same way in all three directories.

I know that this solution is not what you are looking for, but in my experience this method allows you to better manage custom packages, since you can easily add / remove functions.

+2
source

Node.js require allows you

  • Download only one module at a time

  • load modules only synchronously.

Thus, the modular system works in Node.js. But if you want to have the appropriate functionality to minimize, you can flip it yourself, for example,

 var path = require("path"), glob = require("glob"); function requirer(pattern) { var modules = {}, files = glob.sync(pattern); files.forEach(function(currentFile) { var fileName = path.basename(currentFile); fileName = fileName.substring(0, fileName.lastIndexOf(".js")); modules[fileName] = require(currentFile); }); return modules; } 

It depends on the glob , which allows you to use minimization templates to search for files, and then we require the found files, save them in the object and return the object. And it can be used like this

 var modules = requirer('./packages/*/model/*.js'); console.log(modules.cities); 

PS: I'm already working on making this a public module .

+1
source

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


All Articles