Best Require
Best Require is a require()
hook plugin for requiring a module in your project elegantly for Node.js.
;;;
Installation
npm install best-require --save
Introduction
Background
Have you ever coded like this in your application?
// require the 'posts' module;;;;;
When our project contains many layers of directory, the relative path of each module will become complicated, which not only makes us very confused, but also makes the project difficult to maintain.
When faced with the problem, you might tend to find a unified way to access the posts
module, just like me. I used to require modules in this way:
;// other require()...;;;;
ummmm... It's more maintainable than before. But, ROOT_PATH
is ugly, isn't it?
Solution
Let's try to use Best Require, by adding this at the beginning of the app:
process
Now, we can use ~
to represent process.cwd()
in the path:
;;;;;
However, this directory name is still a bit long, which can be shortened by defining the name mapping:
const ROOT_PATH = process;ROOT_PATH apis: ROOT_PATH + '/application/apis' controllers: ROOT_PATH + '/application/apis/controllers';
Then we are able to use :apis
for ~/application/apis
and :controllers
for ~/application/apis/controllers
:
;;;;;
With the release V1.1+, you can also use other keys in the definition of a key-value pair in the name mapping, and our plug-in will automatically handle the keys' dependencies on each other. Therefore, the definition can be simplified as:
ROOT_PATH apis: '~/application/apis' controllers: ':apis/controllers';
Usage
Add this at the beginning of the program:
root_path // [optional] project root directory, defaults to `process.cwd()` name_mapping // [optional] name mapping;
Then you can use:
; // require(root_path + '/(path)');; // require(name_mapping[key] + '/(path)');