๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Frontend/JavaScript

[ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ(JavaScript) ] Pre & Post scripts๋ฅผ ์•Œ์•„๋ณด์ž

by YWTechIT 2023. 1. 3.
728x90

๐Ÿ“ Pre & Post scripts๋ฅผ ์•Œ์•„๋ณด์ž

SEO ์ตœ์ ํ™”๋ฅผ ์œ„ํ•ด Sitemap ์ž‘์—… ์ค‘ package.json ํŒŒ์ผ ๋‚ด๋ถ€์— postbuild script๋ฅผ ์ƒ์„ฑํ•˜๋Š” ์ž‘์—…์ด ์žˆ์—ˆ๋‹ค. ์ด์ „๊นŒ์ง€๋Š” pre์™€ post prefix๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ์ผ์ด ๊ฑฐ์˜ ์—†์–ด ์ด๊ฒƒ๋“ค์ด ํ•˜๋Š” ์—ญํ• ์„ ์ž์„ธํžˆ ์•Œ์ง€ ๋ชปํ–ˆ๋Š”๋ฐ, ์ด๋ฒˆ์— ์•Œ์•„๋ณด๊ณ ์ž npmjs ๊ณต์‹๋ฌธ์„œ๋ฅผ ์‚ดํŽด๋ดค๋‹ค. ๊ณต์‹๋ฌธ์„œ์—์„œ๋Š” pre์™€ post scripts๋ฅผ ๋‹ค์Œ์ฒ˜๋Ÿผ ์ •์˜ํ•˜๊ณ  ์žˆ์—ˆ๋‹ค.

 

To create "pre" or "post" scripts for any scripts defined in the "scripts" section of the package.json, simply create another script with a matching name and add "pre" or "post" to the beginning of them.

 

์š”์•ฝํ•˜์ž๋ฉด pre ๋˜๋Š” post์˜ scripts ์ด๋ฆ„์„ ๋™์ผํ•˜๊ฒŒ ๋งŒ๋“ค๊ณ , prefix์— pre ๋˜๋Š” post์„ ์ถ”๊ฐ€ํ•˜๋ฉด ๋œ๋‹ค๋Š” ๋œป์ธ๋ฐ, ๊ฒฐ๋ก ์ ์œผ๋กœ pre<script>, <script>, <postscript>๊ฐ€ ๋ชจ๋‘ ์กด์žฌํ•œ๋‹ค๋ฉด, ์‹คํ–‰์ˆœ์„œ๋Š” precompress -> comporess -> postcompress๊ฐ€ ๋˜๋Š” ๊ฒƒ์ด๋‹ค.

728x90

์—ฌ๊ธฐ์„œ ์ค‘์š”ํ•œ ๊ฒƒ์€ npm run ์ปค๋งจ๋“œ ์‚ฌ์šฉ์‹œ precompress, compress, postcompress ๋ชจ๋‘๋ฅผ ์ž…๋ ฅํ•˜๋Š”๊ฒƒ์ด ์•„๋‹ˆ๋ผ npm run compress ์Šคํฌ๋ฆฝํŠธ๋งŒ ์ž…๋ ฅํ•˜๋ฉด scripts๊ฐ€ ๋‹ค์Œ ์ˆœ์„œ๋Œ€๋กœ ๋™์ž‘ํ•˜๋Š” ๊ฒƒ์ด๋‹ค.

{
  "scripts": {
    "precompress": "{{ executes BEFORE the `compress` script }}",
    "compress": "{{ run command to compress files }}",
    "postcompress": "{{ executes AFTER `compress` script }}"
  }
}

๋‚˜๋Š” scripts๋ฅผ ๋‹ค์Œ์ฒ˜๋Ÿผ ์ •์˜ํ–ˆ๊ณ , npm run build ์ปค๋งจ๋“œ๋งŒ ์ž…๋ ฅํ•ด๋„ ์ž๋™์œผ๋กœ build -> postbuild์˜ ์ˆœ์„œ๋กœ script๊ฐ€ ์‹คํ–‰๋˜์—ˆ๋‹ค.

{
  "scripts": {
    "build": "next build",
    "postbuild": "next-sitemap",
  }
}

๊ทธ๋ ‡๋‹ค๊ณ  ๋ชจ๋“  scripts๊ฐ€ ์œ„์— ์–ธ๊ธ‰ํ–ˆ๋˜ ์ˆœ์„œ๋กœ ๋™์ž‘ํ•˜๋Š” ๊ฒƒ์€ ์•„๋‹ˆ๋‹ค. ๋ช‡ ๊ฐ€์ง€ ํŠน์ • scripts์—๋Š” ๊ธฐ์กด life cycle๊ณผ๋Š” ๋‹ค๋ฅด๊ฒŒ ์„ค์ •๋˜์–ด์žˆ๋Š”๋ฐ pre<event> -> post<event> -> <event> ์ˆœ์„œ๋กœ ๋™์ž‘ํ•œ๋‹ค.

 

  • prepare, prepublish, prepublishOnly, prepack, postpack, dependencies

ํŠน์ • script์˜ life cycle์„ ๋” ์ž์„ธํžˆ ์•Œ๊ณ  ์‹ถ๋‹ค๋ฉด ํ•˜๋‹จ Reference 2๋ฒˆ ๋งํฌ๋ฅผ ํด๋ฆญํ•ด ๋ณด์ž.

 

Reference

  1. docs.npmjs - pre & post Scripts
  2. docs.npmjs - life-cycle-scripts
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€