Ask Your Question
4

How can ES6 modules be imported using absolute paths in NodeJS without relying on Babel or Webpack?

asked 2022-06-09 11:00:00 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-05-07 08:00:00 +0000

lakamha gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-06-09 11:00:00 +0000

Seen: 9 times

Last updated: May 07 '21