🚀
【Next.js和訳】Advanced Features/Abs Imoports Module path alias
この記事について
この記事は、Advanced Features/Absolute Imports and Module Path Aliasesの記事を和訳したものです。
記事内で使用する画像は、公式ドキュメント内の画像を引用して使用させていただいております。
絶対インポートとモジュールパスエイリアス
Next.js 9.4以降、Next.js はtsconfig.json
and jsconfig.json
"paths"
と"baseUrl"
options を自動的にサポートします。
これらのオプションを使用すると、モジュールエイリアスを構成できます。たとえば、一般的なパターンは、絶対パスを使用するように特定のディレクトリにエイリアスを設定することです。
これらのオプションの便利な機能の 1 つは、vscode などの特定のエディターに自動的に統合されることです。
baseUrl
設定オプションは、プロジェクトのルートから直接インポートすることができます。
この構成の例:
// tsconfig.json or jsconfig.json
{
"compilerOptions": {
"baseUrl": "."
}
}
components/button.js
export default function Button() {
return <button>Click me</button>
}
pages/index.js
import Button from 'components/button'
export default function HomePage() {
return (
<>
<h1>Hello World</h1>
<Button />
</>
)
}
baseUrl
は便利ですが、1 対 1 に一致しない他のエイリアスを追加することもできます。この TypeScript には「パス」オプションがあります。
path
を使用すると、モジュールエイリアスを構成できます。
例:@/components/*
に components/*
を入れる
この構成の例:
// tsconfig.json or jsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/components/*": ["components/*"]
}
}
}
components/button.js
export default function Button() {
return <button>Click me</button>
}
pages/index.js
import Button from '@/components/button'
export default function HomePage() {
return (
<>
<h1>Hello World</h1>
<Button />
</>
)
}
Discussion