Howard
Howard

Reputation: 4604

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.

Upvotes: 26

Views: 57499

Answers (3)

Davey
Davey

Reputation: 2514

Updated answer for 2021.

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

This allows you to add the following to package.json

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

Import in *.js files

import mod1 from '#ok/mod1';
import mod2 from '#info/mod2';

Upvotes: 43

Prusprus
Prusprus

Reputation: 8065

There is an npm package called module-alias that may do what you are looking for.

Upvotes: 15

OrahKokos
OrahKokos

Reputation: 180

The best way to approach this would be to use a global (config) container. In most cases you will have a config file in your application. In this config you can add a property which will be an object containing all absolute paths to files/folders. Because config files are used at the start of you application, you just do the following:

var config = require("./config.js");
//config = {... , path: {"someModule": "/absolute/path/to", "someModule2": "/absolute/path/to"...}}
global.CONFIG_CONTAINER = config

Later on in your application you can just use

var myModule = require(CONFIG_CONTAINER.path.someModule)
// + concat if you are looking for a file

In case you have some complex paths and you need a more dynamic system, you can always implement a function inside the config that will build paths for you. ( config.makePath = function(){...} ) That should take care of it in a nutshell.

Upvotes: -6

Related Questions