TypeScriptにおいて import { NuxtAuthHandler } from "#auth";
のようなインポート文を見かけることがある。この#auth
のような例をパスエイリアスと呼ぶ。
パスエイリアスを利用することで、相対パスでコンポーネントを指定する場合に比べてディレクトリ構造の変化に強くなるしわかりやすくなる。
パスエイリアスには#
だけでなく、@
や~
など、自由に指定できる。
パスエイリアスは tsconfig.json 内の compilerOptions.paths にて定義する。
Nuxt3においてはプロジェクトルートの tsconfig.json
は{ "extends": "./.nuxt/tsconfig.json" }
のような内容となっており、ビルド時に自動的に適切な値で生成してくれる。
実際に試したところ、./.nuxt/tsconfig.json
の compilerOptions.paths は以下のような内容となっていた。
{ "compilerOptions": { ... "paths": { "~": [ ".." ], "~/*": [ "../*" ], "@": [ ".." ], "@/*": [ "../*" ], "~~": [ ".." ], "~~/*": [ "../*" ], "@@": [ ".." ], "@@/*": [ "../*" ], "assets": [ "../assets" ], "public": [ "../public" ], "public/*": [ "../public/*" ], "#app": [ "../node_modules/.pnpm/nuxt@3.10.1_vite@5.1.1/node_modules/nuxt/dist/app" ], "#app/*": [ "../node_modules/.pnpm/nuxt@3.10.1_vite@5.1.1/node_modules/nuxt/dist/app/*" ], "vue-demi": [ "../node_modules/.pnpm/nuxt@3.10.1_vite@5.1.1/node_modules/nuxt/dist/app/compat/vue-demi" ], "#vue-router": [ "./vue-router-stub" ], "#imports": [ "./imports" ], "#build": [ "." ], "#build/*": [ "./*" ], "#components": [ "./components" ] } }, ...