Absolute Imports and Module path aliases

Examples

Next.js automatically supports the tsconfig.json and jsconfig.json "paths" and "baseUrl" options since Next.js 9.4.

Note: jsconfig.json can be used when you don’t use TypeScript

Note: you need to restart dev server to reflect modifications done in tsconfig.json / jsconfig.json

These options allow you to configure module aliases, for example a common pattern is aliasing certain directories to use absolute paths.

One useful feature of these options is that they integrate automatically into certain editors, for example vscode.

The baseUrl configuration option allows you to import directly from the root of the project.

An example of this configuration:

  1. // tsconfig.json or jsconfig.json
  2. {
  3. "compilerOptions": {
  4. "baseUrl": "."
  5. }
  6. }
  1. // components/button.js
  2. export default function Button() {
  3. return <button>Click me</button>
  4. }
  1. // pages/index.js
  2. import Button from 'components/button'
  3. export default function HomePage() {
  4. return (
  5. <>
  6. <h1>Hello World</h1>
  7. <Button />
  8. </>
  9. )
  10. }

While baseUrl is useful you might want to add other aliases that don’t match 1 on 1. For this TypeScript has the "paths" option.

Using "paths" allows you to configure module aliases. For example @/components/* to components/*.

An example of this configuration:

  1. // tsconfig.json or jsconfig.json
  2. {
  3. "compilerOptions": {
  4. "baseUrl": ".",
  5. "paths": {
  6. "@/components/*": ["components/*"]
  7. }
  8. }
  9. }
  1. // components/button.js
  2. export default function Button() {
  3. return <button>Click me</button>
  4. }
  1. // pages/index.js
  2. import Button from '@/components/button'
  3. export default function HomePage() {
  4. return (
  5. <>
  6. <h1>Hello World</h1>
  7. <Button />
  8. </>
  9. )
  10. }