Last active
July 21, 2021 20:55
-
-
Save stuart-haas/d2f7897580cfffc525c69ca89ee7afb7 to your computer and use it in GitHub Desktop.
Global function to resolve paths for NodeJS modules
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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