Absolute Imports and Module Path Aliases
Examples
Next.js has in-built support for the "paths" and "baseUrl" options of tsconfig.json and jsconfig.json files.
These options allow you to alias project directories to absolute paths, making it easier to import modules. For example:
1// before2import { Button } from '../../../components/button'34// after5import { Button } from '@/components/button'
Good to know:
create-next-appwill prompt to configure these options for you.
Absolute Imports
The baseUrl configuration option allows you to import directly from the root of the project.
An example of this configuration:
tsconfig.json
1{2"compilerOptions": {3"baseUrl": "."4}5}
components/button.tsx
1export default function Button() {2return <button>Click me</button>3}
app/page.tsx
1import Button from 'components/button'23export default function HomePage() {4return (5<>6<h1>Hello World</h1>7<Button />8</>9)10}
Module Aliases
In addition to configuring the baseUrl path, you can use the "paths" option to โaliasโ module paths.
For example, the following configuration maps @/components/* to components/*:
tsconfig.json
1{2"compilerOptions": {3"baseUrl": ".",4"paths": {5"@/components/*": ["components/*"]6}7}8}
components/button.tsx
1export default function Button() {2return <button>Click me</button>3}
app/page.tsx
1import Button from '@/components/button'23export default function HomePage() {4return (5<>6<h1>Hello World</h1>7<Button />8</>9)10}
Each of the "paths" are relative to the baseUrl location. For example:
1// tsconfig.json or jsconfig.json2{3"compilerOptions": {4"baseUrl": "src/",5"paths": {6"@/styles/*": ["styles/*"],7"@/components/*": ["components/*"]8}9}10}
1// pages/index.js2import Button from '@/components/button'3import '@/styles/styles.css'4import Helper from 'utils/helper'56export default function HomePage() {7return (8<Helper>9<h1>Hello World</h1>10<Button />11</Helper>12)13}