مقدمة/بناء تطبيقك/التهيئة/الاستيراد المطلق واختصارات مسار الوحدات (Absolute Imports and Module Path Aliases)
الاستيراد المطلق واختصارات مسار الوحدات (Absolute Imports and 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 />
</>
)
}اختصارات الوحدات
بالإضافة إلى تكوين مسار 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>
)
}