Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have path alias in nodejs?

Let's say i have following codes:

var mod1 = require('../../../../ok/mod1');
var mod2 = require('../../../info/mod2');

It's not pretty coding like above, i am wondering if there is a way to configure the root resolver just like webpack-resolve-root in nodejs?

So far as i know, the NODE_PATH can be used to replace the root of node_modules, but that's not what i want. I'd like to have the resolver to resolve multiple folders in order.

like image 567
Howard Avatar asked Oct 19 '15 12:10

Howard


People also ask

What are path aliases?

🎉 Path aliasing or aliases are preconfigured names used to replace long paths in files and resolve to certain directories on a codebase.

How do I write a path in node JS?

js: var fs = require('fs') var newPath = "E:\\Thevan"; var oldPath = "E:\\Thevan\\Docs\\something. mp4"; exports. uploadFile = function (req, res) { fs. readFile(oldPath, function(err, data) { fs.

What is __ Dirname in node?

__dirname: It is a local variable that returns the directory name of the current module. It returns the folder path of the current JavaScript file. Difference between process.cwd() vs __dirname in Node.js is as follows: process.cwd()

What does module alias do?

Create aliases of directories and register custom module paths in NodeJS like a boss! Enough of this madness! WARNING: This module should not be used in other npm modules since it modifies the default require behavior!


1 Answers

Updated answer for 2021.

nodejs subpath imports have been added in: v14.6.0, v12.19.0

This allows for you to add the following to package.json

"imports": {
  "#ok/*": "./some-path/ok/*"
  "#info/*": "./some-other-path/info/*"
},

and in your .js

import mod1 from '#ok/mod1';
import mod2 from '#info/mod2';
like image 188
Davey Avatar answered Sep 22 '22 19:09

Davey