incutonez
incutonez

Reputation: 3331

Node Subpath Imports External Directory

In Vite/WebPack, we can define path aliases fairly easily, and we can even use the @ to define these. However, in an ESM Node app, it's not as easy. There's module-alias, but it's a little outdated, and doesn't work for ESM packages. All of this led me to Subpath Imports.

Subpath Imports seem to work just fine (except I can't use @ instead of #) with files/directories in the package.json's directory, but it doesn't seems to work with directories outside. e.g. this is my imports config in package.json:

"imports": {
  "#api/*": "./*",
  "#shared/*": "../shared/*"
}

The #api works properly, but the #shared does not. Is there some sort of extra config that I'm unaware of, or is this not possible with Subpath Imports? I know the docs say it is possible to define internal package import maps that only apply to import specifiers from within the package itself, so if it's not possible, what are my alternatives?

Upvotes: 3

Views: 1580

Answers (1)

incutonez
incutonez

Reputation: 3331

I think I found a solution that works a little better. I'm using an npm workspace, which actually allows me to use the workspaces as if they're absolute paths. My directory structure is as follows:

root/
  api/
    app.js
    package.json
  shared/
    test.js
    package.json
  ui/
    package.json
  package.json

In the root package.json, I have specified the workspaces config to be the following:

"workspaces": [
  "ui",
  "api",
  "shared"
]

And then in app.js, I can reference something from shared like import test from "shared/test.js". I didn't realize this added benefit of workspaces, but it definitely solves the issue I was having.

Upvotes: 1

Related Questions