-
항해 99 5기 TIL_24항해 99 2022. 2. 3. 04:26
▶ Today I Learned
<CS 공부>
[require와 IIFE]
[require의 동작 원리]
require는 module.js라는 파일 내 정의된 메서드로써 ()내 지정된 경로의 파일을 불러온다.
그 다음 해당 파일의 코드를 IIFE(즉시 실행 함수표현식)화 하고, 코드 내 값을 module.exports라는 object를 통해 return해주게 된다.
이때 파일 내 정의된 코드를 IIFE화 함으로써 해당 코드가 다른 모듈이나 코드에 간섭을 받지 않으며 동시에 require에 라는 함수로 접근은 가능하게 해주는 것이다.
좀 더 상세한 설명은 아래에 적혀있다.
[npm require 함수]
require는 외부의 모듈을 끌어오기 위한 함수이며 require()에서 ()안에 추가할 모듈의 파일 경로 값을 받는다. 경로에서 ./는 같은 파일 내 동등한 위치에 있다는 상대경로, ../는 같은 파일 내 있지 않은 절대경로를 나타낸다.
cf) 만약 경로 값에 ./를 추가해주지 않으면 node.js 자체 라이브러리에서 모듈을 찾는다.
(모듈이란 외부의 영향을 받지 않는, 재사용을 위한 독립적인 코드들의 묶음이다.)
예를 들어 a라는 폴더 내 동일한 경로위치에 app.js와 any.js라는 파일이 있다.
any.js는 다음과 같다.
// any.jsconsole.log(1) function showNumber() { console.log(2) }
여기서 node app.js로 app.js를 실행하면 콘솔에 1이 찍히지 않는다. 둘이 같은 폴더에 있어도 서로 연결되지 않기 때문이다.
이럴때 any.js에 있는 코드를 수행하기 위해서 app.js에 다음이 코드를 추가한다.
require("./any.js");
이렇게 되면 app.js실행 시 콘솔에 1이 찍히게 된다.
그렇다면 이대로 app.js와 any.js가 완전히 연결된 것일까?
만약 그렇다면 app.js에서 showNumber()를 호출하는 것 역시 작동하여 콘솔에는 1과 2가 출력되어야 할 것이다.
하지만 이 경우 콜솔 2는 나타나지 않고 에러가 발생한다.
require를 했다고 해서 any.js내의 API에 대한 접근권까지 생기는 것은 아니기 때문이다.
해당 API를 사용하려면 any.js측에서 다음의 코드를 추가하여야 한다.
module.exports = showNumber()
module.exports는 node에서 만들어 낸 하나의 property인데 이는 비어있다. 위 처럼 특정 메서드(여기선 showNumber())를 대입해주면 그 property에 입혀지게 되는 것이다.
또한 위와 달리 showNumber라는 특정 함수를 내보내고 싶은 것이기에 이때는 app.js에서 다음과 같이 코드를 작성하여야 한다.
const showNum = require("./any.js"); showNum();
이후 app.js를 실행시키면 비로소 any.js의 showNumber()를 실행시킬 수 있는 것이다.
[IIFE]
IIFE(immidiately invoked function expression)는 즉시 실행되는 함수 표현식을 나타낸다.
공식문서에 따르면 형태는 다음과 같다.
(function () { statements })();
Hello world라는 구문을 쓰면 아래와 같은 형태이며 곧바로 실행되어 결과 값이 출력된다.
(function () { console.log('Hello World') })(); // Hello World
위 괄호를 ( )()로 본다면 첫번째 괄호는 괄호 내 변수에 접근하는 것을 불가능하게 하고 전역함수를 오염시키는 것을 막아준다.
예를 들어 아래와 같은 코드가 있다.
(function () { // some initiation codelet firstVariable; let secondVariable; })();
이런 함수표현식을 만들어놓으면 해당 식 안의 firstVariable과 secondVariable은 해당 식안에서만 선언되고 동작한다.
해당 식이 끝나면 모두 사라진다. 따라서 해당 함수표현식이 속한 파일이나 바깥에서 끌어오는 모듈 내 동일한 이름의 변수들 (firstVariable과 secondVariable)이 선언되어 있더라도 해당 표현식 안의 것과 서로 영향을 주지 않는다.
파일 간 연결이 많아질수록 수많은 함수와 변수들이 겹칠 수 있는데 IIFE는 이를 방지하는 역할을 해준다.
그래서 이런 구조가 require와 module.exports에서도 사용되는 것이다.
참고자료:
https://velog.io/@doondoony/javascript-iife
https://m.blog.naver.com/jdub7138/221022257248
[ajax vs fetch vs axios]
Ajax
Asynchronous JavaScript And XML의 약자,
Ajax를 통해 서버와 비동기적으로 통신함으로 인해 우리는 전체 웹페이지를 다시 불러오는 동기 방식과는 다르게 점진적으로 해당 부분의 사용자 인터페이스를 갱신할 수 있다.
여기서 ajax와 JQuery를 연관지어서 생각할 수 있다.
실제로 우리가 써왔던 ajax 소스코드를 보면 다음과 같이 JQuery가 들어있다.
이렇게 둘을 연관지어 말하는 이유는 Ajax를 JQuery 방식으로 사용하는 것이 훨씬 간편하기 때문이다.
Ajax자체는 1999년에 정립되어 쓰여왔지만 순수 ajax방식은 코드가 지저분했고 jquery로 정립된 것이 훨씬 깔끔하고 단순했다. 그리하여 널리 쓰이게 된 것이다.
fetch()
ES6부터 내장된 자바스크립트의 라이브러리,
Promise 기반으로 만들어져 response 데이터를 다루기 쉽다.
axios
Node.js와 브라우저를 위한 HTTP통신 라이브러리,
비동기 HTTP통신을 가능하게 해준다.
return 값이 Promise 형태이기에 fetch()와 마찬가지로 response를 다루기 쉽다.
또한 코드의 생김새가 비교적 간단하고 ajax와 모양이 비슷하다.
예시)
axios({ method: 'post', url: '/user/info', data: { Name: Hong, Height: 180 } });
장단점
ajax
장점: Jquery를 통해 비교적 쉽게 구현 가능, Error, Success, Complete 구문을 통해 실행 흐름 조절 용이
단점: Jquery를 사용한 소스코드 필요, Promise 기반이 아님
fetch
장점: 내장 라이브러리이기에 별도의 모듈 설치 필요 X, promise 기반으로 데이터를 다루기 쉬움
단점: 일부 브라우저의 호환성이 떨어짐, JSON으로 변환해주는 과정이 필요, 상대적으로 axios에 비해
기능이 부족함
axios
장점: response timeout이라는 fetch에는 없는 기능 존재, promise 기반으로 만들어져 데이터 관리가 편리, 크로스 브라우징에 신경을 많이 썼기 때문에 브라우저 호환성이 좋음
단점: 사용을 위해 npm을 통해 모듈 설치 필요
현업에서는 axios를 많이 사용한다는 이야기들을 들었다. 브라우저 호환성이 높고 기능이 우수한 편이기 때문이라는 의견들이 있다. 다만 react-native처럼 업데이트가 잦은 경우엔 fetch를 사용하는 것이 훨씬 안정적일 수 있다. 내장된 라이브러리이기에 업데이트에도 기본적으로 알맞게 작동할 수 있는 반면, 모듈은 프레임워크의 업데이트에 따라 호환되지 않는 부분이 간혹 생길 수 있기 때문이다.
참고자료: https://velog.io/@kysung95/개발상식-Ajax와-Axios-그리고-fetch
https://cocoon1787.tistory.com/756
<홈페이지 구현>
열심히 밤을 새가며 박차를 가하고 있다.
현재 회원가입 기능 구현을 완료하였으며 로그인 기능 구현 막바지에 있다.
이후에도 댓글기능과 로그인 정보 조회 등 구현할 기능이 5가지 정도 남았다.
마저 열심히 해야지..
▶ 느낀 점
초반에 axios라는 새로운 기술을 적용하느라 시간을 꽤 소비하였다. 다음 과제에는
우선 이전 코드 리팩토링보단 구현을 먼저 해두는 게 좋겠다. 아무래도 아직 실력과 지식이 충분치 않아 제한시간 안에
처음부터 다시 하기에는 무리가 있었던 듯 하다.
또한 집중력이 조금 흐트러졌던 순간도 꽤 있었는데 앞으로 집중시간을 조금만 더 늘릴 수 있도록 해야겠다.
휴대폰을 조금 멀리두고 코드를 쳐다보고 구글링하는 것에 좀 더 신경을 쏟자.
▶ 공부 시 참고 링크들
https://m.blog.naver.com/jdub7138/221022257248
https://developer.mozilla.org/en-US/docs/Glossary/IIFE
'항해 99' 카테고리의 다른 글
항해 99 5기 TIL_26 (0) 2022.02.05 항해 99 5기 TIL_25 (0) 2022.02.04 항해 99 5기 TIL_23 (0) 2022.02.02 항해 99 5기 TIL_22 (0) 2022.02.01 항해 99 5기 WIL_3 (0) 2022.01.30