You will need NodeJS installed in your machine/project in order to load both the path
and fs
libraries.
npm i node
npm i import-alias-file
This npm library eases the process of importing files within a nodejs project. The way it works it's similar to NextJS!.
I made it after getting tired of using ../
multiple times when I needed to use a function that was placed in a different file!
const express = require("express");
const lookFile = require("import-alias-file");
const { getBlogs, getBlog, createBlog } = lookFile("@/controllers/blogs"); // <- That
// Instead of this, require('../../../../controllers/blogs');
const Blog = lookFile("@/models/Blog"); // <- That
// Instead of this, require('../../../models/Blog);
const router = express.Router();
router.route("/").get(getBlogs).post(createBlog);
router.route("/:id").get(getBlog);
module.exports = router;
You can specify the file extension as well.
// This is the same
const { getBlogs, getBlog, createBlog } = lookFile("@/controllers/blogs");
const Blog = lookFile("@/models/Blog");
// as this
const { getBlogs, getBlog, createBlog } = lookFile("@/controllers/blogs.js");
const Blog = lookFile("@/models/Blog.js");
The extensions supported so far are .js
, .json
, and .ts
.
The import-alias-file
community can be found on GitHub Discussions where you can ask questions and voice ideas.
- Kevin Fonseca (@kirasiris)
Dude, I'm broke. If you find this useful, please don't hesitate to help me maintain it!.
This library is still too young. I accept any help you guys can provide. The goal is to make the functionality NextJS uses into NodeJS. Please feel free to share your knowledge!
I'm available to work with you guys. If you need a developer who specializes in MongoDB, Express, ReactJS/NextJS, NodeJS, Php and MySQL, then I'm you're guy!. Reach out to me at kuaf1998@gmail.com
.
You can also check my portfolio at my personal blog.
A list of co-authors that have helped improve this amazing library!