๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

TIL

Next.js ์—์„œ module import ์‹œ alias ์‚ฌ์šฉํ•˜๊ธฐ (์ ˆ๋Œ€๊ฒฝ๋กœ)

Next.js ๊ณต์‹ ๋ฌธ์„œ์—์„œ๋„ ์†Œ๊ฐœํ•˜๊ณ  ์žˆ๋‹ค.

 

Advanced Features: Absolute Imports and Module Path Aliases | Next.js

Configure module path aliases that allow you to remap certain import paths.

nextjs.org

์–ผ๋งˆ ์ „ ๊ธฐ์ˆ ๋ฉด์ ‘ ๊ณผ์ œ๋ฅผ ์ œ์ถœํ–ˆ๋Š”๋ฐ ๋ฉด์ ‘ ๋ณผ ๋•Œ ์™œ ์ƒ๋Œ€๊ฒฝ๋กœ๋กœ ์ž‘์„ฑํ–ˆ๋ƒ๊ณ  ๋ฌผ์–ด๋ณด์…จ๋‹ค.
๊ทธ๋™์•ˆ์€ ๊ทธ๋ ‡๊ฒŒ ํฐ ํ”„๋กœ์ ํŠธ ์ž‘์—…ํ•ด๋ณธ ์ ์ด ์—†๊ณ  ๋””๋ ‰ํ† ๋ฆฌ ๊นŠ์ด๋„ ์•„์ฃผ ๊นŠ์€ ์ ์ด ์—†์–ด์„œ ํฌ๊ฒŒ ์ ˆ๋Œ€๊ฒฝ๋กœ๋กœ ์ž‘์„ฑํ•ด์•ผ์ง€ ํ•˜๊ณ  ์ƒ๊ฐํ•ด๋ณด์ง€ ์•Š์•˜๋Š”๋ฐ ์ด๋ฒˆ์— ์ƒˆ๋กœ์šด ์‚ฌ์ด๋“œ ํ”„๋กœ์ ํŠธ๋ฅผ ์ง„ํ–‰ํ•˜๋ฉด์„œ๋Š” ์ ˆ๋Œ€๊ฒฝ๋กœ๋กœ ์„ค์ •ํ•˜๊ณ  ์ž‘์—…ํ•ด๋ณด๋ ค๊ณ  ์ฐพ์•„๋ดค๋‹ค. 

์•„๋ž˜์˜ ์„ค๋ช…์€ JS ๊ธฐ์ค€์ด๋‹ค.

- jsconfig.json๋ฅผ root์— ์ƒ์„ฑํ•ด์ค€๋‹ค. 

- jsconfig.json์—๋Š” ์•„๋ž˜์™€ ๊ฐ™์ด ์ž‘์„ฑ (์ด๊ฑด ์˜ˆ์‹œ์ด๊ณ  ์ž์‹ ์ด "@components/" ์ด ๋ถ€๋ถ„์€ ์ž์‹ ์ด ์›ํ•˜๋Š”๋Œ€๋กœ ์ž‘์„ฑ)

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@components/*": [
        "components/*"
      ],
      "@layouts/*": [
        "layouts/*"
      ],
      "@styles/*": [
        "styles/*"
      ]
    }
  }
}

baseUrl์€ ํ”„๋กœ์ ํŠธ์˜ root์—์„œ ๋ฐ”๋กœ import ํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•ด์ฃผ๊ธฐ ๋•Œ๋ฌธ์— ์ ˆ๋Œ€๊ฒฝ๋กœ ์‚ฌ์šฉ์ด ๊ฐ€๋Šฅํ•ด์ง„๋‹ค. 
paths๋Š” ๋ชจ๋“ˆ alias๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•ด์ฃผ๋Š”๋ฐ components/* ๊ฒฝ๋กœ๋Š” @components/*๋กœ ๋งคํ•‘๋œ๋‹ค. 

์•„๋ž˜์˜ ๊ธ€์„ ์ฝ์–ด๋ณด๋Š” ๊ฒƒ๋„ ๋„์›€์ด ๋œ๋‹ค. 
https://dev.to/whitep4nth3r/how-to-avoid-using-relative-path-imports-in-next-js-eki

 

How to avoid using relative path imports in Next.js

Does this look familiar? ๐Ÿคฏ import MyComponent from "../../../../../components/MyComponent"; import...

dev.to

- ์„œ๋ฒ„๋ฅผ ์žฌ์‹œ์ž‘ํ•˜์—ฌ jsconfig.json์ด ์ ์šฉ๋˜๋„๋ก ํ•œ๋‹ค.

../../../../../๋ฅผ ํ”ผํ•  ์ˆ˜ ์žˆ๋‹ค. ์•„์ฃผ ํŽธํ•˜๊ณ  ๊ฐ„๊ฒฐํ•˜๋ฉฐ ์ง๊ด€์ ์ด๋‹ค. ๐Ÿ‘