Skip to content

Instantly share code, notes, and snippets.

@stuart-haas
Last active July 21, 2021 20:55
Show Gist options
  • Save stuart-haas/d2f7897580cfffc525c69ca89ee7afb7 to your computer and use it in GitHub Desktop.
Save stuart-haas/d2f7897580cfffc525c69ca89ee7afb7 to your computer and use it in GitHub Desktop.
Global function to resolve paths for NodeJS modules
// This is ugly
// const Service = require('../app/services/Service');
// Try this instead
// const Service = alias('service/Service')
const path = require('path');
const aliases = {
config: './config',
bootstrap: './bootstrap',
errors: './app/errors',
app: './app',
http: './app/http',
models: './app/models',
controllers: './app/http/controllers',
services: './app/services',
routes: './routes',
middleware: './app/http/middleware',
};
alias = function(dir) {
const dirArr = dir.split('/');
if(dirArr.length > 1) {
const mod = dirArr.pop();
const newDirArr = dirArr.join('/');
if(aliases[newDirArr]) {
return require(path.resolve(aliases[newDirArr], mod));
}
return require(path.resolve(newDirArr, mod));
}
if(aliases[dirArr[0]]) {
return require(path.resolve(aliases[dirArr[0]]));
}
return require(path.resolve(dir));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment