Closed6
tsc で transpile 時に paths alias を相対 path に変換したい
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`;
typescript-transform-paths を使う
Transform compiled source module resolution paths using TypeScript's paths config, and/or custom resolution paths.
tsconfig の paths の設定値に基づいて、compile 後のコードの path を変換してくれる。
ts-patch を install
typescript-transform-paths を利用するために、ts-patch が必要になるので install する。
yarn add -D ts-patch
typescript-transform-paths を install する
yarn add -D add -D typescript-transform-paths
- 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 }
]
}
}
tsc を ts-patch に置き換え
Via commandline: Simply use tspc (instead of tsc)
あとは、実行する際の command を tsc から ts-patch を利用するように tspc に置き換える
- "compile": "tsc",
+ "compile": "tspc",
これで完了!
このスクラップは2023/10/20にクローズされました