はるさめ.dev

VSCode で import 時にエイリアスの path suggestion が表示されない

に公開

背景

VSCode では、TypeScript > Suggest: Paths が有効になっていると、import 時にパスのサジェストを表示してくれます。

しかし、Next.js のプロジェクトで開発している際、tsconfig.json の compilerOptions.paths の設定が有効化されず、サジェストが表示されない状況が発生しました。

解決方法

tsconfig.json の compilerOptions.baseUrl を設定する。

{
  "compilerOptions": {
    "target": "ES2017",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "noEmit": true,
    "baseUrl": ".”,  // 追加
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "paths": {
      "@/*": ["./src/*"]
    }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
  "exclude": ["node_modules"]
}

補足

tsconfig.json の compilerOptions.paths は、compilerOptions.baseUrl からの相対パスを指定する必要があるため、compilerOptions.baseUrl の設定が必須です。

TypeScript の公式リファレンス(Paths - TypeScript: TSConfig リファレンス)にも compilerOptions.baseUrl は必須と記載されていますが、Next.js のスキャフォールドで生成される tsconfig.json にはデフォルトでこの設定が含まれていません。そのため、パスサジェストが正しく動作しないようです。

なお、VSCode の拡張機能「Path IntelliSense」を使用している場合も同様の問題が発生します。

コメント