DEV Community

Stuart Haas
Stuart Haas

Posted on

Path aliases with Vanilla Node JS

I've been working on a side-project that is more or less an experimental attempt to make a Laravel-like clone with the ExpressJS framework. Along the way, I thought to myself, "Is it possible to use path aliases with out Typescript?". I did some researching and founds lot of answers but no real, tangible solutions. I came up with something on my own. Although it's not terribly pretty or clever, it does what I want it to.

// 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));
};

Take a look and let me know what you think.

Thanks for reading!

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post