绝对导入与模块路径别名

示例

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>Click me</button>
}

模块别名

除了配置 baseUrl 路径外,您还可以使用 "paths" 选项为模块路径设置"别名"。

例如,以下配置将 @/components/* 映射到 components/*

tsconfig.json 或 jsconfig.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/components/*": ["components/*"]
    }
  }
}
export default function Button() {
  return <button>Click me</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