ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Modern JavaScript npm & Module
    FrontEnd/Node.js 2023. 3. 16. 02:06

     

    버전설명


    1. npm (node package manager)

    • 모듈 : Application을 구성하는 개별적 요소 (일반적으로 파일단위로 분리, 필요에 따라 로드)
    • 모듈별(기능별)로 분리되어 있을시 개발효율성과 유지보수성 향상 (javascript은 부재)
    • RequireJs : AMD 방식으로 비동기적으로 동작하는 모듈로더
    • Node.js는 CommonJS 방식을 따름
    • CLI (Command line interface) : Node.js에서 사용할 수 있는 모듈들을 패키지화하여 모아둔 저장소 역할, 패키지설치 및 관리 역할
    • package.json : 프로젝트 정보와 패키지의 의존성을 관리, 해당파일로 팀내에 동일한 배포환경을 빠르게 구축할 수 있음
    //macOS의 경우 전역에 설치된 패키지 경로 : /usr/local/lib/node_modules
    
    //패키지설치
    //로컬 설치
    $ npm install <package-name> //지역설치의 경우 해당 프로젝트 내에서만 사용
    
    // 전역 설치
    $ npm install -g <package-name>
    
    //개발 설치
    $ npm install --save-dev <package-name>
    
    //package.json의 모든 패키지 설치
    $ npm install
    
    //로컬/개발 패키지 제거
    $ npm uninstall <package-name>
    
    //전역 패키지 제거
    $ npm uninstall -g <package-name>
    
    //패키지 업데이트
    $ npm update <package-name>
    
    //전역설치 패키지확인
    $ npm ls -g --depth=0
    
    //ex) node-emoji 설치
    $ npm install node-emoji
    
    //package.json 생성
    $ npm init -y //y옵션 추가시 기본설정값으로 생성
    //dependencies항목에 프로젝트가 의존하는 패키지의 이름과 버전을 명시 (의존성 설정)
    
    //dependencies에 설치된 패키지 이름과 버전 기록
    $ npm install --save node-emoji
    $ npm install --save-dev <package>
    
    //Semantic versioning : @버전 추가시 패키지버전을 지정하여 설치가능
    $ npm install node-emoji@1.5.0
    
    //--save-exact 옵션지정시 설치된 버전을 범위 지정없이 기록
    
    //package.json scripts property 실행
    $ npm start
    
    //start 이외의 scipts 실행
    $ npm run <script-name>
    
    //전역패키지 설치폴더 확인
    $ npm root -g
    
    //파인더 오픈
    $ open /usr/local/lib/node_modules
    
    //패키지 정보 참조
    $ npm view <package-name>
    
    //ex) eslint-config-airbnb와 함께 설치해야 하는 다른 패키지 확인
    $ npm view eslint-config-airbnb@latest peerDependencies
    
    //버전확인
    $ npm -v
    
    //npm 명령어설명
    $ npm help <command>

     


    2. Module

    • CommonJS & AMD(Asynchronous Module Definition) : JavaScript를 Client-side에 국한하지 않고 범용적으로 사용하기위해 고안됨
    • 기본적으로 Node.js는 CommonJs 방식을 채택
    • Module은 파일과 1:1 대응하며 독립적인 실행영역(Scope)를 가짐 (전역변수의 중복문제가 발생하지 않음)
    • module.exports or exports object를 통해 외부로 express
    • require function을 이용하여 import

     


    3. exports

     

     exports / module.exports
    exports exports 객체에는 값을 할당할 수 없고
    공개할 대상을 exports 객체에 프로퍼 또는 메소드로 추가
    exports 객체에 추가한 프로퍼티와 메소드가 담긴
    객체가 전달됨
    module.exports module.exports 객체에
    하나의 값(원시 타입, 함수, 객체)만을 할당
    module.exports 객체에
    할당한 값이 전달됨

     

    //1.exports 예시 : circle.js
    const { PI } = Math;
    
    exports.area = (r) => PI * r * r;
    exports.circumference = (r) => 2 * PI * r;
    
    //require 예시(import) : app.js
    const circle = require('./circle.js'); // == require('./circle')
    
    console.log(`지름이 4인 원의 면적: ${circle.area(4)}`);
    console.log(`지름이 4인 원의 둘레: ${circle.circumference(4)}`);
    
    //실행시
    $ node app
    지름이 4인 원의 면적: 50.26548245743669
    지름이 4인 원의 둘레: 25.132741228718345
    
    
    
    //2.module.exports 예시 : foo.js
    module.exports = function(a, b) {
      return a + b;
    };
    
    //app.js
    const add = require('./foo');
    
    const result = add(1, 2);
    console.log(result); // => 3

     

     


    4. require

    //1.directory structure 예시
    
    project/
    ├── app.js
    └── module/
        ├── index.js
        ├── calc.js
        └── print.js
        
    //2.exports 정의 
    //module 하위 import
    const myModule = require('./module');
    
    //module/index.js
    //객체할당방식
    module.exports = {
      calc: require('./calc'),
      print: require('./print')
    };
    
    //module/calc.js
    //메소드방식
    module.exports = {
      add (v1, v2) { return v1 + v2 },
      minus (v1, v2) { return v1 - v2 }
    };
    
    //module/print.js
    module.exports = {
      sayHello() { console.log('Hi!') }
    };
    
    
    //3.실행시 : app.js
    const myModule = require('./module');
    
    //module/calc.js 기능
    const result = myModule.calc.add(1, 2);
    console.log(result);
    
    //module/print.js 기능
    myModule.print.sayHello();
    
    
    //4.Core Module, npm을 통한 외부패키지의 경우 패스를 명시하지 않음
    const http = require('http');
    const mongoose = require('mongoose');

     

    'FrontEnd > Node.js' 카테고리의 다른 글

    Modern JavaScript Node.js  (1) 2023.03.14

    댓글

Designed by Tistory.