반응형

# Node.js 학습_npm(패키지 매니저)

1. npm이란

  • npm이란 Node Package Manager의 약자로, 노드의 패키지 매니저이다.
  • 다른 사람들이 만든 소스 코드들을 모아둔 저장소.
  • 남의 코드를 사용하여 프로그래밍 가능
  • 이미 있는 기능을 다시 구현할 필요가 없어 효율적이다.
  • 오픈 소스 생태계를 구성중
  • 패키지 : npm에 업로드된 노드 모듈
  • 모듈이 다른 모듈을 사용할 수 있듯, 패키지도 다른 패키지를 사용할 수 있다.
  • 의존 관계라고 부른다.

### package.json

  • 현재 프로젝트에 대한 정보와 사용 중인 패키지에 대한 정보를 담은 파일.
  • 같은 패키지라도 버전별로 기능이 다를 수 있으므로 버전을 기록해두어야 함
  • 동일한 버전을 설치하지 않으면 문제가 생길 수 있다.
  • 노드 프로젝트 시작 전 package.json부터 만들고 시작함 (package.json 생성 명령어 : npm init)
1. npm init
입력 시 아래와 같이 나옴.
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help init` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.

2. npm init 후 아래와 같은 문구 나오면 항목에 맞게 작성.
package name: (publish) npmtest
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author: lhyeonho
license: (ISC) MIT
About to write to C:\work\work_http_server_c\publish\package.json:

{
  "name": "npmtest",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "lhyeonho",
  "license": "MIT"
}


Is this OK? (yes) yes

### package.json 속성들

  • package name : 패키지의 이름. package.json의 name 속성에 저장된다.
  • version : 패키지의 버전. npm의 버전은 다소 엄격하게 관리된다.
  • entry point : 자바스크립트 실행 파일 진입점. 보통 마지막으로 module.exports를 하는 파일을 지정한다. package.json의 main 속성에 저장된다.
  • test command : 코드를 테스트할 때 입력할 명령어를 의미. package.json scripts 속성 안의 test 속성에 저장된다.
  • git repository : 코드를 저장해둔 Git 저장소 주소를 의미한다. 나중에 소스에 문제가 생겼을 떄 사용자들이 이 저장소에 방문해 문제를 제기할 수도 있고, 코드 수정본을 올릴 수도 있다. package.json의 repository 속성에 저장된다.
  • keywords : 키워드는 npm 공식 홈페이지(https://npmjs.com)에서 패키지를 쉽게 찾을 수 있게 해준다. package.json의 keywords 속성에 저장된다.
  • license : 해당 패키지의 라이선스를 넣어주면 된다.

### npm 스크립트 (=터미널에 입력하는 명령어에 별명을 붙여주는 것)

  • npm init이 완료되면 폴더에 package.json이 생성된다.
{
  "name": "npmtest",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "lhyeonho",
  "license": "MIT"
}
  • npm run [스크립트명]으로 스크립트 실행
1. 스크립트에 설정해놓은 test를 run 할 경우 아래와 같이 나옴.
npm run test

> npmtest@1.0.0 test C:\work\work_http_server_c\publish
> echo "Error: no test specified" && exit 1

"Error: no test specified" 
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! npmtest@1.0.0 test: `echo "Error: no test specified" && exit 1`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the npmtest@1.0.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm WARN Local package.json exists, but node_modules missing, did you mean to install?

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Hyeonho\AppData\Roaming\npm-cache\_logs\2021-10-05T12_07_03_187Z-debug.log

C:\work\work_http_server_c\publish>
  • 아래와 같이 스크립트에 "start"를 넣어 실행 가능. (해당 스크립트는 run이 생략된 npm start로 실행 가능)
{
  "name": "npmtest",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index"
  },
  "author": "lhyeonho",
  "license": "MIT"
}

### 패키지 설치하기

  • express 설치하기 (아래와 같이 입력하여 설치하게 되면 package.json에 dependencies 추가됨.
npm i express
{
  "name": "npmtest",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index"
  },
  "author": "lhyeonho",
  "license": "MIT",
  "dependencies": {
    "express": "^4.17.1"
  }
}
  • cookie-parser body-parser 동시에 설치도 가능.
npm i cookie-parser body-parser
{
  "name": "npmtest",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index"
  },
  "author": "lhyeonho",
  "license": "MIT",
  "dependencies": {
    "body-parser": "^1.19.0",
    "cookie-parser": "^1.4.5",
    "express": "^4.17.1"
  }
}
  • npm i -D : devDependencies는 개발 시에만 쓰이는 패키지를 저장해 두는 것.
npm i -D nodemon
{
  "name": "npmtest",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index"
  },
  "author": "lhyeonho",
  "license": "MIT",
  "dependencies": {
    "body-parser": "^1.19.0",
    "cookie-parser": "^1.4.5",
    "express": "^4.17.1"
  },
  "devDependencies": {
    "nodemon": "^2.0.13"
  }
}

 

2. node_modules와 npx, SenVer

  • 배포 시에는 보통 node_modules를 지우고 배포 함. (용량을 많이 차지함)
  • package.json 이 있는 폴더에서 npm i 입력 시 package.json에 있는 dependencies 항목들이 다시 설치됨.
npm i
  • npm i -g : g는 global로 전역 설치. 이렇게 설치하면 dependencies에 기록되지 않음. (요즘엔 -g 설치 기피함 -> package.json에 없는 항목은 사용여부 추측이 어려움)
npm i -g rimraf
  • 여즘엔 -g 설치 기피하여 아래와 같이 설치.
npm i -D rimraf 

npx rimraf node_modules
  • npx : node package excute 로 node 패키지 실행 한다는 것.
  • package-lock.json 의 경우 버전 문제를 막아주는 파일 임.

### SemVer 버저닝

  • 노드 패키지의 버전은 SemVer(유의적 버저닝) 방식을 따름
  • Major(주 버전) , Minor(부 버전), Patch(수 버전)
  • 노드에서는 배포를 할 때 항상 버전을 올려야 함
  • Major : 하위 버전과 호환되지 않은 수정 사항이 생겼을 때 올림
  • Minor : 하위 버전과 호환되는 수정 사항이 생겼을 때 올림
  • Patch : 기능에 버그를 해결했을 때 올림
1.0.0

첫 번째 숫자 : Major	// 하위 호환되지 않는 변경 사항
두 번째 숫자 : Minor	// 하위 호환되는 변경 사항
세 번째 숫자 : Patch	// 간단한 버그 수정
  • 버전 기호 사용하기
버전 앞에 기호를 붙여 의미를 더함

^1.1.1 : 패키지 업데이트 시 minor 버전까지만 업데이트 됨(2.0.0버전은 안됨)

~1.1.1 : 패키지 업데이트 시 patch 버전까지만 업데이트 됨(1.2.0버전은 안됨)

>=, <=, >, <는 이상, 이하, 초과, 미만.

@latest : 최신을 의미

@next : 가장 최신 배포판 사용 가능(불안정함)

알파/베타/RC 버전이 존재할 수도 있음
(1.1.1-alpha.0 / 2.0.0-beta.1 / 2.0.0-rc.0)
  • 예시
1. 첫 번째 자리만 고정
^1.1.1


2. 두 번째 자리만 고정
~1.1.1


3. 세 번째 자리까지 모두 고정
1.1.1

 

3. npm 명령어

### 기타 명령어

  • npm outdated : 어떤 패키지에 기능 변화가 생겼는지 알 수 있음
  • npm uninstall 패키지명 : 패키지 삭제(npm rm 패키지명 으로 사용 가능)
  • npm search 검색어 : npm 패키지를 검색할 수 있다. (npmjs.com에서도 가능)
  • npm info 패키지명 : 패키지의 세부 정보 파악 가능
  • npm adduser : npm에 로그인을 하기 위한 명령어(npmjs.com에서 회원가입)
  • npm whoami : 현재 사용자가 누구인지 알려줌
  • npm logout : 로그인한 계정을 로그아웃
  • npm version 버전 : package.json의 버전을 올림 (이렇게 하면 git에 commit도 됨)
  • npm deprecate [패키지명][버전] [메시지] : 패키지를 설치할 때 경고 메시지를 띄우게 함 (오류가 있는 패키지에 적용)
  • npm publish : 자신이 만든 패키지를 배포
  • npm unpublish : 자신이 만든 패키지를 배포 중단(배포 후 24시간 내에만 가능). 다른 사람이 내 패키지를 사용하고 있는데 배포가 중단되면 문제가 생기기 때문.
  • npm ls 패키지명 : 내 프로젝트가 어떤 패키지를 사용하고 있는지 찾고 싶을 때 사용.
  • 그외 명령어는 https://docs.npmjs.com 의 CLI Commands에서 확인 가능. (https://docs.npmjs.com)
 

npm Docs

Documentation for the npm registry, website, and command-line interface

docs.npmjs.com

 

4. npm 배포

  • package.json이 있는 위치로 이동.
  • npm publish 입력하여 npm 배포.
C:\work\work_http_server_c>cd publish

C:\work\work_http_server_c\publish>npm publish 
npm notice 
npm notice package: npmtest35303011-3046@1.0.0
npm notice === Tarball Contents === 
npm notice 439B package.json
npm notice === Tarball Details === 
npm notice name:          npmtest35303011-3046
npm notice version:       1.0.0
npm notice package size:  345 B
npm notice unpacked size: 439 B
npm notice shasum:        9630f88ba8cd0fc537f32dd8ce6ed539b635c352
npm notice integrity:     sha512-ocG3QNKpShdyK[...]565CrPYe3ywTQ==
npm notice total files:   1
npm notice 
npm ERR! code E403
npm ERR! 403 403 Forbidden - PUT https://registry.npmjs.org/npmtest35303011-3046 - Package name triggered spam detection; if you believe this is in error, please contact support at https://npmjs.com/support
npm ERR! 403 In most cases, you or one of your dependencies are requesting
npm ERR! 403 a package version that is forbidden by your security policy.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Hyeonho\AppData\Roaming\npm-cache\_logs\2021-10-05T12_53_36_119Z-debug.log

C:\work\work_http_server_c\publish>
  • npm info 설정한 패키지명(예)npmtest35303011-3046) 로 확인 가능.
  • npm unpublish 패키지명 으로 삭제 가능.
반응형

+ Recent posts