الاستيراد المطلق وعناوين مسارات الوحدات (Module Path Aliases)
يحتوي Next.js على دعم مدمج لخيارات "paths"
و "baseUrl"
في ملفات tsconfig.json
و jsconfig.json
.
تتيح لك هذه الخيارات تعيين أدلة المشروع إلى مسارات مطلقة، مما يجعل استيراد الوحدات أسهل. على سبيل المثال:
// قبل
import { Button } from '../../../components/button'
// بعد
import { Button } from '@/components/button'
معلومة مفيدة: سيقوم
create-next-app
بطلب تكوين هذه الخيارات لك.
الاستيراد المطلق
يتيح لك خيار التكوين baseUrl
الاستيراد مباشرة من جذر المشروع.
مثال على هذا التكوين:
{
"compilerOptions": {
"baseUrl": "."
}
}
import Button from 'components/button'
export default function HomePage() {
return (
<>
<h1>Hello World</h1>
<Button />
</>
)
}
import Button from 'components/button'
export default function HomePage() {
return (
<>
<h1>Hello World</h1>
<Button />
</>
)
}
عناوين الوحدات (Module Aliases)
بالإضافة إلى تكوين مسار baseUrl
، يمكنك استخدام خيار "paths"
لـ"تعيين" مسارات الوحدات.
على سبيل المثال، يقوم التكوين التالي بتعيين @/components/*
إلى components/*
:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/components/*": ["components/*"]
}
}
}
import Button from '@/components/button'
export default function HomePage() {
return (
<>
<h1>Hello World</h1>
<Button />
</>
)
}
import Button from '@/components/button'
export default function HomePage() {
return (
<>
<h1>Hello World</h1>
<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>
)
}