본문 바로가기

Next.js

Next.js 12-4 Configuring Absolute Imports and Module Path Aliases

    Next.js는 tsconfig.json과 jsconifg.json 파일의 "paths" 및 "baseUrl" 옵션을 기본적으로 지원한다. 이 옵션을 사용하면 프로젝트 디렉토리를 절대 경로에 별칭으로 지정하여 모듈을 더 쉽게 가져올 수 있다.

// before
import { Button } from '../../../components/button'

// after
import { Button } from '@/components/button'

 

  • Absolute Imports

  baseUrl 구성 옵션을 사용하면 프로젝트의 루트에서 직접 가져올 수 있다.

// tsconfig.json or jsconfig.json

{
  "compilerOptions": {
    "baseUrl": "."
  }
}
// components/button.tsx

export default function Button() {
  return <button>Click me</button>
}
// app/page.tsx

import Button from 'components/button'

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

 

  • Module Aliases

  baseUrl 경로를 구성하는 것 외에도 "경로" 옵션을 사용하여 모듈 경로를 "별칭"할 수 있다. 예를 들어 다음 구성은 @/components/*를 components/*에 매핑한다.

// tsconfig.json or jsconfig.json

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/components/*": ["components/*"]
    }
  }
}
// components/button.tsx

export default function Button() {
  return <button>Click me</button>
}
// app/page.tsx

import Button from '@/components/button'

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

  각 '경로'는 baseUrl 위치에 상대적이다.

// tsconfig.json or 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>
  )
}

'Next.js' 카테고리의 다른 글

Next.js 12-6 Configuring src Directory  (0) 2023.06.26
Next.js 12-5 Configuring MDX  (0) 2023.06.26
Next.js 12-3 Configuring Environment Variables  (0) 2023.06.22
Next.js 12-2 Configuring ESLint  (0) 2023.06.22
Next.js 12-1 Configuring TypeScript  (0) 2023.06.19