(Daily / TIL 02.24) commonJS ๋ชจ๋“ˆ

Seung Ho Yoonยท2021๋…„ 2์›” 25์ผ
0

I studied this today

  • npm, package.json
  • ํ™”์‚ดํ‘œ ํ•จ์ˆ˜
  • CommonJS

package.json

npm ๋ชจ๋“ˆ์„ ํ™œ์šฉํ•˜๊ธฐ ์œ„ํ•ด ํ•ด๋‹น ๋ชจ๋“ˆ์— ๋Œ€ํ•œ ์ •๋ณด๋ฅผ ๋‹ด์€ ํŒŒ์ผ
์ฆ‰, ํ”„๋กœ์ ํŠธ ์ „๋ฐ˜์— ๊ด€ํ•œ ์ •๋ณด๊ฐ€ ๋‹ด๊ฒจ์žˆ๋‹ค.

npm : node.js ์ƒํƒœ๊ณ„์˜ ํŒจํ‚ค์ง€ ๋งค๋‹ˆ์ €

{
  "name": "modern-javascript-koans",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  // ํ”„๋กœ์ ํŠธ์— ๊ด€ํ•œ ์ •๋ณด
  "scripts": {
    "test": "mocha modern-js-koans/*.js --sort",
    "report": "mocha modern-js-koans/*.js --sort --reporter @mochajs/json-file-reporter",
    "submit": "codestates-submission"
  },
  "keywords": [],
  "author": "codesatates",
  //์Šคํฌ๋ฆฝํŠธ๋Š” CLI์—์„œ ์‚ฌ์šฉ๊ฐ€๋Šฅํ•œ ๋ช…๋ น๋“ค
  
  "dependencies": {
    "@codestates-cc/submission-npm": "^1.1.1"
  },
  "devDependencies": {
    "@mochajs/json-file-reporter": "^1.2.1",
    "chai": "^4.2.0",
    "mocha": "^8.2.0",
    "sinon": "^9.0.3"
  }
  // ๊ฐœ๋ฐœ๊ณผ ๊ด€๋ จ๋œ dependency๋“ค
}

์‚ฌ์šฉ์ „ ์ ํžŒ ๋ชจ๋“ˆ์„ ๋‹ค์šด๋กœ๋“œ => $ npm install
๋ชจ๋“ˆ์„ ์ด์šฉํ•˜์—ฌ test ์‚ฌ์šฉ๋ฒ• => $ npm run test
๋ชจ๋“ˆ์„ ์ด์šฉํ•˜์—ฌ ์ œ์ถœ => $ npm run submit

ํ™”์‚ดํ‘œ ํ•จ์ˆ˜

ํ•จ์ˆ˜ํ‘œํ˜„์‹
const add = function (x, y) {
  return x + y
}
ํ™”์‚ดํ‘œ ํ•จ์ˆ˜๋กœ
const add = (x, y) =>  {
  return x + y;
}  

ํ™”์‚ดํ‘œ ํ•จ์ˆ˜ ๊ทœ์น™

ํ•จ์ˆ˜ ๋ณธ๋ฌธ(body)์— ๋ฆฌํ„ด๋ฌธ ํ•œ์ค„ ๋งŒ ์žˆ์„ ๊ฒฝ์šฐ return์„ ์ƒ๋žตํ• ์ˆ˜ ์žˆ๋‹ค, ์ฃผ์˜ ํ•ด์•ผ ๋ ์ ์€ { } (์ค‘๊ด„ํ˜ธ)๋Š” ์‚ฌ์šฉํ•˜๋ฉด ์•ˆ๋œ๋‹ค.

๋งŽ์ด ์“ฐ๋Š” ํ™”์‚ดํ‘œ ํ•จ์ˆ˜์˜ ํด๋กœ์ ธํ•จ์ˆ˜ ์˜ˆ์‹œ

ํ•จ์ˆ˜ ํ‘œํ˜„์‹
const adder = function(x) {
  return function(y) {
    return x + y
  }
}

ํ™”์‚ดํ‘œ ํ•จ์ˆ˜๋กœ
const adder = x => {
  return y => {
   return x + y;
  }
} 

CommonJS

๋ชจ๋“  ๋ชจ๋‘˜์€ ๋…๋ฆฝ์ ์ธ ๊ณต๊ฐ„์„ ๊ฐ€์ ธ์•ผ ํ•œ๋‹ค.
commonJS๋Š” ํ•˜๋‚˜์˜ ํ•จ์ˆ˜๋ผ๊ณ  ์ƒ๊ฐ.

module.exports๋ฅผ ์‚ฌ์šฉํ•ด JSํŒŒ์ผ์„ ๋ชจ๋“ˆํ™” ์‹œํ‚จ๋‹ค.
exports๋Š” module.exports๋ฅผ ์ถ•์•ฝํ™” ์‹œํ‚จ๊ฒƒ ์ด๋‹ค.

<hello.js>
let x = 10;
module.exports.x = 20;

requier๋ฅผ exports ๊ฐ์ฒด๋ฅผ ๋ถˆ๋Ÿฌ์˜จ๋‹ค.

const get = require("./hello.js")
// get์—๋Š” 20์ด ๋‹ด๊ธด๋‹ค.
profile
Frontend Developer

0๊ฐœ์˜ ๋Œ“๊ธ€