絕對路徑導入與模組路徑別名

範例

Next.js 內建支援 tsconfig.jsonjsconfig.json 檔案中的 "paths""baseUrl" 選項。

這些選項讓您可以將專案目錄設定為絕對路徑的別名,使模組導入更加容易。例如:

// 之前
import { Button } from '../../../components/button'

// 之後
import { Button } from '@/components/button'

須知create-next-app 會提示您設定這些選項。

絕對路徑導入

baseUrl 設定選項讓您可以直接從專案根目錄導入模組。

以下是一個設定範例:

tsconfig.json 或 jsconfig.json
{
  "compilerOptions": {
    "baseUrl": "."
  }
}
export default function Button() {
  return <button>點擊我</button>
}

模組別名

除了設定 baseUrl 路徑外,您還可以使用 "paths" 選項來「別名」模組路徑。

例如,以下設定將 @/components/* 映射到 components/*

tsconfig.json 或 jsconfig.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/components/*": ["components/*"]
    }
  }
}
export default function Button() {
  return <button>點擊我</button>
}

每個 "paths" 都是相對於 baseUrl 的位置。例如:

// tsconfig.json 或 jsconfig.json
{
  "compilerOptions": {
    "baseUrl": "src/",
    "paths": {
      "@/styles/*": ["styles/*"],
      "@/components/*": ["components/*"]
    }
  }
}
// pages/index.js
import Button from '@/components/button'
import '@/styles/styles.css'
import Helper from 'utils/helper'

export default function HomePage() {
  return (
    <Helper>
      <h1>Hello World</h1>
      <Button />
    </Helper>
  )
}

On this page