9

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 ?

Poyoman
  • 1,652
  • 1
  • 20
  • 28

2 Answers2

12

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';
GOTO 0
  • 42,323
  • 22
  • 125
  • 158
  • Nice thank you for your answer, i will give it a try tomorrow :) – Poyoman Nov 29 '21 at 23:14
  • This is working fine. I'm a bit disappointed with 'index.js' not managed automatically, but seems due to ( https://nodejs.org/api/esm.html#mandatory-file-extensions ) This is a bit of topic, but do you have any idea on how to enforce automatic '.js / index.js' management ? – Poyoman Nov 30 '21 at 15:22
  • I found an answer => https://stackoverflow.com/questions/37159533/es6-ecmascript-2015-modules-import-index-js – Poyoman Nov 30 '21 at 15:26
  • 1
    Unfortunately, it seems that there is no way for import names to match multiple files, like require can do by appending ".js", ".json", "/index.js", [etc.](https://nodejs.org/api/modules.html#all-together) – GOTO 0 Nov 30 '21 at 17:09
3

note that if you are using typescript, you'll have to update your tsconfig as well. Let's say you want to use @helpers/whatever instead of ../../../helpers/whatever


"baseUrl": "src", # or whatever your base directory is
"paths": {
   "@helpers/*": ["helpers/*"]
},

And if you are using jest, you will also need to update your jest config

moduleNameMapper: {
    '^@helpers/(.*)$': '<rootDir>/src/helpers/$1',
},
Pierre Olivier Tran
  • 1,669
  • 4
  • 24
  • 40