typescriptswcswc-compiler

swc not resolving import path aliases


I have a typescript project which I'm transpiling with swc. I'm having trouble getting swc to resolve path aliases defined in either tsconfig.json or .swcrc. The module aliases are resolved properly by eslint and when running ts-node when swc is not specified as the compiler.

Given this pull request, it seems that swc is both supposed to resolve tsconfig.json and has support for path aliases defined in .swcrc. However, it seems people experienced similar issues to mine following this feature, though it was two years ago and I can't imagine there hasn't been a solution since.

Also on a weird sort of side-note the author of the PR which implements TSConfigResolver that I linked earlier mentions in an issue a year after his PR was merged that swc "doesn't look at tsconfig". Though this shouldn't be the source of my problem though because I'm specifying the same path aliases in .swcrc

The swc documentation is horribly vague and doesn't mention anything about module aliases or resolving tsconfig, besides that jsc.baseUrl and jsc.paths are compilation options and they match tsconfig syntax.

Any help or guidance would be appreciated, thank you!

tsconfig.json

{
  "compilerOptions": {
    "target": "es2020",
    "module": "ESNext",
    "moduleResolution": "node",
    "baseUrl": "./",
    "paths": {
      "$lib/*": ["src/lib/*"]
    },
    "outDir": "./dist",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  },
  "ts-node": {
    "swc": true
  },
  "exclude": ["node_modules", "dist"]
}

.swcrc

{
  "$schema": "https://json.schemastore.org/swcrc",
  "jsc": {
    "baseUrl": "./",
    "paths": {
      "$lib/*": ["src/lib/*"]
    }
  },
  "module": {
    "type": "es6"
  }
}

package.json

{
  "type": "module",
  "devDependencies": {
    "@swc/cli": "^0.1.62",
    "@swc/core": "^1.3.35",
    "ts-node": "^10.9.1",
    "typescript": "^4.9.5"
  }
}

I receive the following error when running swc . -d ./dist from the project root directory:

CustomError: Cannot find package '$lib' imported from /root/projects/example/src/index.ts


Solution

  • It was fixed in recent pull request. Make sure you specified your paths in both tsconfig.json and .swcrc https://github.com/swc-project/swc-node/pull/723