Absolute Imports and Module path aliases
Next.js automatically supports the and jsconfig.json
"paths"
and "baseUrl"
options since .
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.
An example of this configuration:
// components/button.js
export default function Button() {
return <button>Click me</button>
}
While is useful you might want to add other aliases that don’t match 1 on 1. For this TypeScript has the "paths"
option.
An example of this configuration:
// tsconfig.json or jsconfig.json
{
"baseUrl": ".",
"paths": {
"@/components/*": ["components/*"]
}
}
// pages/index.js
export default function HomePage() {
return (
<>
<h1>Hello World</h1>
<Button />
</>