Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have aliases with nodejs import

I have a project using node.js v16, and more and more npm libs are not anymore compatible with require, and need to be used with import.

Until now i was using package.json to have my root directory as alias

  // package.json
  "dependencies": {
    "~src": "file:.",
  }

And in my source code

const someCode = require('~src/absolute/path/someCode');

This is not working with import, and with tests i made, i haven't found any solution to make it works with import.

Have you already met that kind of problem ? And found a solution about it ?

like image 320
Poyoman Avatar asked Dec 12 '25 02:12

Poyoman


1 Answers

I believe the preferred way to alias folders in current versions of Node is using subpath imports.

For example, you could alias your root folder as #src (import mappings must always start with #). To do so, add the following imports section in your package.json:

"imports": {
  "#src/*": "./*.js"
}

Now, supposing you have a file some/path/someCode.js in your package, you could import it like this:

import someCode from '#src/some/path/someCode';

You can also map subfolders with the same syntax:

"imports": {
  "#src/*": "./*.js",
  "#somepath/*": "./some/path/*.js"
}

And in the importing file:

import someCode from '#somepath/someCode';
like image 159
GOTO 0 Avatar answered Dec 14 '25 15:12

GOTO 0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!