Develop/JavaScript

[JavaScript] 모듈

dawonny 2021. 7. 20. 18:54
728x90
반응형

코드의 재활용성을 높이고 유지보수를 쉽게 할수 있는 방법에는 여러가지가 있다

그중에 하나가

하나의 코드를 여러개의 파일로 분리하는 것이다

장점은..

-자주 사용되는 코드를 별도의 파일로 만들어서 필요할 때마다 재활용할 수 있다

-코드를 개선하면 이를 사용하는 모든 애플리케이션의 동작이 개선된다

-필요한 로직만을 로드해서 메모리의 낭비를 줄일 수 있다

순수 자바스크립트에서는 모듈이라는 개념이 분명하게 있는건 아니지만

js가 구동되는 호스트환경(구동되는 환경)에 따라서 다른 모듈화 방법이 제공된다

여기 생활코딩에서 나오는건 웹브라우저에서 로직을 모듈화 하는 방법을 알아볼것임


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
</head>
<body>
    <script>
        function welcome(){
            return 'Hello world'
        }
        alert(welcome());
    </script>
</body>
</html>

이런 코드가 있다고 가정하자

welcome 함수가 필요할때마다 정의해서 사용하는건 낭비가 된다

함수 welcome을 모듈화 해보자

greeting.js 라는 파일을 새로 만들었다

function welcome(){
    return 'Hello world';
}

그리고 main.html의 내용을 이렇게 바꾸었다

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <script src="greeting.js"></script>
</head>
<body>
    <script>
        alert(welcome());
    </script>
</body>
</html>

script 태그 안에 있는 건 브라우저에 의해서 javascript로 인식이 된다

src 속성에 있는 파일을 다운받아 실행시킨다.

그래서 welcome 함수를 greeting.js에서 가져와서 실행 시킬수있다.


node.js에서 모듈을 로드하는 방법

node.cricle.js(로드될 대상)

var PI = Math.PI;
  
exports.area = function (r) {
return PI * r * r;
};
  
exports.circumference = function (r) {
return 2 * PI * r;
};

node.demo.js (로드의 주체)

var circle = require('./node.circle.js');
console.log( 'The area of a circle of radius 4 is '
           + circle.area(4));

require를 통해 불러와서 circle에 저장하고

출력한 모습이다


라이브러리

:모듈과 비슷한 개념, 자주 사용되는 로직을 재사용하기 편하도록 정리한 일련의 코드들의 집합

유명 라이브러리인 jQuery 를 사용하는 방법

jQuery 홈페이지에서 파일을 다운로드 받는다.

http://jquery.com/

 

jQuery

What is jQuery? jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers.

jquery.com

jQuery 메뉴얼을 이용해서 사용법을 파악한다.

http://api.jquery.com/

 

jQuery API Documentation

jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. If you're new t

api.jquery.com

아래는 jQuery를 이용한 예제이다.

<!DOCTYPE html>
<html>
<head>
    <script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
    <ul id="list">
        <li>empty</li>
        <li>empty</li>
        <li>empty</li>
        <li>empty</li>
    </ul>
    <input id="execute_btn" type="button" value="execute" />
    <script type="text/javascript">
     $('#execute_btn').click(function(){//버튼을 누를때 바뀌게 하고싶음
        $('#list li').text('coding everybody');//id값이 list인 태그의 li들을 가리킴
     })
    </script>
</body>
</html>
​

 

 

참고 : 생활코딩 - 자바스크립트

728x90
반응형