node.jsjson

Directory import not supported


Before now I was using CommonJS and module-alias but I want to move over to ES modules and switch to the natively supported import mappings, so I refactored to this in my package.json:

{
   "imports": {
      "#http/*": "./http/",
      "#cloud/*": "./cloud/",
      "#constants": "./constants"
    } 
}

However when I do this in my server.js:

import APIClient from '#http/apiClient';

I get the following error:

Directory import /Users/me/sampleApp/http/ is not supported

This was working perfectly fine with module-alias what am I doing wrong now?


Solution

  • With these subpath patterns, you need to specify the wildcard on both sides, and the extension too:

    {
      "imports": {
        "#http/*": "./http/*",
        "#cloud/*": "./cloud/*",
        "#constants": "./constants.js"
      } 
    }
    
    import APIClient from '#http/apiClient.js';
    

    * maps expose nested subpaths as it is a string replacement syntax only.

    All instances of * on the right hand side will then be replaced with this value, including if it contains any / separators.