Closed6

tsc で transpile 時に paths alias を相対 path に変換したい

nbstshnbstsh

monorepo 環境で bundle はしないで tsc で transpile するだけの package を作成する際に、paths alias を使いたい。

が、tsc は transpile 時に paths alias の import に関しては変換しないので、ここを変換できるようにしたい。

tsconfig.json
    "baseUrl": "./",
    "paths": {
      "@/*": ["./src/*"],
    }
import { MyComponent } from '@/components`;

これを tsc すると、

import { MyComponent } from  '@/components`;

'@/components` のままになる。

こうしたい↓

import { MyComponent } from  '../../../components`;
nbstshnbstsh

typescript-transform-paths を使う

Transform compiled source module resolution paths using TypeScript's paths config, and/or custom resolution paths.

tsconfig の paths の設定値に基づいて、compile 後のコードの path を変換してくれる。

https://github.com/LeDDGroup/typescript-transform-paths#typescript-transform-paths

nbstshnbstsh

typescript-transform-paths を install する

yarn add -D add -D typescript-transform-paths
  1. tsconfig で設定

plugins{ "transform": "typescript-transform-paths" } を追加。

{
  "compilerOptions": {
    "baseUrl": "./",
    // Configure your path mapping here
    "paths": {
      "@utils/*": ["utils/*"]
    },
    // Note: To transform paths for both the output .js and .d.ts files, you need both of the below entries
    "plugins": [
      // Transform paths in output .js files
      { "transform": "typescript-transform-paths" },

      // Transform paths in output .d.ts files (Include this line if you output declarations files)
      { "transform": "typescript-transform-paths", "afterDeclarations": true }
    ]
  }
}
nbstshnbstsh

tsc を ts-patch に置き換え

Via commandline: Simply use tspc (instead of tsc)

あとは、実行する際の command を tsc から ts-patch を利用するように tspc に置き換える

-    "compile": "tsc",
+    "compile": "tspc", 
このスクラップは2023/10/20にクローズされました