Search code examples
node.jsimportaliasrequire

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 ?


Solution

  • 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';