Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I require modules with patterns in the path?

How can I include all files in nodeJS like

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

like as

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

same like grunt is loading files.

like image 352
9me Avatar asked Mar 21 '15 07:03

9me


People also ask

Which is the correct way to define a module pattern?

In software engineering, the module pattern is a design pattern used to implement the concept of software modules, defined by modular programming, in a programming language with incomplete direct support for the concept.

Where does require look for modules?

The require function will look for files in the following order. NPM Modules. It will look in the node_modules folder. Local Modules.

What does path module do?

The Path module provides a way of working with directories and file paths.

Can you mix import and require?

Cases where it is necessary to use both “require” and “import” in a single file, are quite rare and it is generally not recommended and considered not a good practice. However, sometimes it is the easiest way for us to solve a problem. There are always trade-offs and the decision is up to you.


1 Answers

You can't (or at least you shouldn't)

In order to do this, you would have to overload node's native require function, which is highly inadvisable.

The CommonJS pattern might seem tedious to you, but it's a very good one and you shouldn't try to break it just because you saw shortcuts in other languages/frameworks.

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

like image 168
maček Avatar answered Oct 12 '22 12:10

maček