Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

NodeJS currently does not support importing modules using absolute paths as a default feature. However, there are third-party modules such as "app-module-path" or "module-alias" which can enable the usage of absolute paths.

Here's an example using module-alias:

  1. Install module-alias:
npm install --save module-alias
  1. At the start of your main script, set the alias:
require('module-alias/register') // This will look for package.json to resolve the absolute paths. If you don't have a package.json just specify the base/root directory
  1. In your package.json file, specify the aliases and their corresponding paths under the "module-alias" key:
"module-alias": {
  "@root": ".",
  "@src": "./src"
}
  1. Now you can import your modules using absolute paths:
import { someFunction } from '@src/module'

Note: This method is not recommended as it requires modifying the configuration and can cause confusion within the project. It is better to use relative paths or a build tool such as Webpack or Babel to handle absolute paths.