Home > Back-end >  Is there a way to configure node.js to use absolute paths for imports?
Is there a way to configure node.js to use absolute paths for imports?

Time:10-13

What I'm basically trying to achieve is to be able to do:

import {thingOne, thingTwo} from 'functions/myFunctions.js'

instead of

import {thingOne, thingTwo} from '../../functions/myFunctions.js'

Paths are obviously hypothetical. The idea is that the functions directory exists in the root of the project - in the same directory as package.json.

I've been able to achieve this whilst using React by specifying a baseUrl in jsconfig.json, but that does nothing whilst working with a standard nodejs project. I'd prefer not to use any extra packages/dependencies for this.

I've also tried setting the environment variable NODE_PATH to './', as I've seen suggested elsewhere, but that didn't change anything either. If it's relevant, I'm using Ubuntu via WSL2, and Node.js v17.7.2. Thank you

CodePudding user response:

You can use the subpath patterns feature with subpath imports.

Consider this example:

./package.json:

{
  "name": "so-74050411",
  "version": "0.1.0",
  "type": "module",
  "imports": {
    "#root/*.mjs": "./*.mjs"
  },
  "license": "MIT"
}

./src/module.mjs:

export function greet (name) {
  console.log(`Hello ${name ?? 'world'}`);
}

./src/subdir_a/subdir_b/module_b.mjs:

import {greet} from '#root/src/module.mjs';

greet('Stack Overflow');

Then, running from the project root directory in the terminal:

$ node --version
v16.18.0

$ node src/subdir_a/subdir_b/module_b.mjs
Hello Stack Overflow

CodePudding user response:

If you are using typescript you can do something like this:

tsconfig.json

 ...
 "paths": {
      "data/*": ["src/data/*"],
      "helpers/*": ["src/helpers/*"],
    }
  },

here's some resources that can help you: https://plusreturn.com/blog/how-to-configure-a-path-alias-in-a-react-typescript-app-for-cleaner-imports/

  • Related