tsconfigのpathsよりもsubpath importsを使おう
TypeScriptのpathsは、import解決のエイリアスを設定できるTypeScriptの独自機能。
code: tsconfig.json
{
"compilerOptions": {
"paths": {
"@/*": "./src/*"
}
},
}
と書くと、import { Button } from "@/components/Button"で/src/components/Button.tsにあるモジュールをimportできる。
Subpath importsはNode.jsの機能で、同様にimport解決のエイリアスを設定できる。
code:package.json
{
"imports": {
"#*": "./src/*.ts"
}
}
と書くと、import { Button } from "@/components/Button"で/src/components/Button.tsにあるモジュールをimportできる。
どちらも似たような機能だが、できることとルールに違いがある。
基本的にはsubpath importの方を使ったほうが良いのでそうしましょう。
tsconfigのpaths
TypeScriptのモジュール解決にのみ影響する
tscでのコンパイルで置き換えてくれるわけではない!!
pathsに"@/*": ["./src/*"]と設定があったとして、import { Button } from "@/components/Button"をコンパイルしてもimport { Button } from "@/components/Button"のままである
当然ランタイムは"@/components/Button"を解決できないのでランタイムエラーになる
Next.jsとか使っていると忘れちゃうけどそうなんですよ
バンドル時に置き換えてくれるバンドラもあるが、大抵プラグインか個別での設定が必要になる
例えばviteだとvite-tsconfig-pathsがよく使われている
https://www.npmjs.com/package/vite-tsconfig-paths
webpackだとtsconfig-paths-webpack-plugin
https://www.npmjs.com/package/tsconfig-paths-webpack-plugin
turbopackは組み込みで持っている?
https://nextjs.org/docs/app/api-reference/turbopack#module-resolution
その他ツールも同様で、プラグインを入れたり、tsconfigのパスを指定したり、同じエイリアスを手動で指定したりする必要があることが多い
jest, vitest
ts-nodeなどのtsそのまま実行するやつ系
madgeなどの依存関係可視化系
knipは標準でtsconfigを見てくれるみたい
elecdeer.iconだるい!!
書きかけ