NPM이란?
NPM은 자바스크립트 코드를 구성하고 공유하는 도구로 자바스크립트로 된 모든 것을 패키지로 관리하는 프로그램
NPM은 Node.js를 설치하면 자동으로 설치되기 때문에 따로 설치할 필요 없이 편리하게 사용 가능
NPM은 자바스크립트 프로그래밍 언어를 위한 패키지 관리자이며, Node.js에서 실행되는 자바스크립트 프로그램을 관리
패키지는 서비스에 업로드 된 노드 모듈을 의미하는데, 하나의 모듈이 다른 모듈을 사용할 수 있는 것처럼, 하나의 패키지가 다른 패키지를 사용이 가능
NPM은 특히 Node.js로 개발되는 프론트엔드 프로젝트에서는 필수적인 도구라고 할 수 있는데, Vue, React와 같이 자바스크립트 프레임워크를 사용하는 경우에는 NPM으로 쉽게 프로젝트의 버전 관리가 가능
NPM 사용 방법
NPM 시작
Node.js 프로젝트를 처음 시작하는 경우라면 다음의 명령어로 초기화
$ npm init
npm init
명령어로 초기화를 해주면 package.json
파일이 자동으로 생성되는데, package.json
파일의 구조는 아래와 같다.
{
"name": "sample",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
package.json
에서 scripts
라는 부분이 있는데, 이 scripts
에 shell script
를 지정해 두면 필요할 때 실행시킬 수 있어. 앞의 샘플 코드에는 test
라는 스크립트가 지정되어 있는데, npm test
를 입력하여 해당 스크립트를 실행하면 다음과 같은 메세지가 출력되는 것을 확인 할 수 있다.
$ npm test
만약 새로운 스크립트를 지정하고 싶다면 다음과 같이 새로운 라인에 스크립트를 추가하고 실행
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"msg": "echo \"Hello, World\""
},
NPM 버전 확인
NPM의 버전을 확인하고 싶다면 다음의 명령어로 확인 가능
$ npm -v
NPM 명령어
NPM의 명령어 목록을 확인하고 싶다면 다음과 같이 npm만 입력하고 엔터를 누르면 npm 명령어와 함께 사용할 수 있는 옵션을 확인 가능
$ npm
npm <command>
Usage:
npm install install all the dependencies in your project
npm install <foo> add the <foo> dependency to your project
npm test run this project's tests
npm run <foo> run the script named <foo>
npm <command> -h quick help on <command>
npm -l display usage info for all commands
npm help <term> search for help on <term> (in a browser)
npm help npm more involved overview (in a browser)
All commands:
access, adduser, audit, bin, bugs, cache, ci, completion,
config, dedupe, deprecate, diff, dist-tag, docs, doctor,
edit, exec, explain, explore, find-dupes, fund, get, help,
hook, init, install, install-ci-test, install-test, link,
ll, login, logout, ls, org, outdated, owner, pack, ping,
pkg, prefix, profile, prune, publish, rebuild, repo,
restart, root, run-script, search, set, set-script,
shrinkwrap, star, stars, start, stop, team, test, token,
uninstall, unpublish, unstar, update, version, view, whoami
Specify configs in the ini-formatted file:
C:\Users\attre\.npmrc
or on the command line via: npm <command> --key=value
More configuration info: npm help config
Configuration fields: npm help 7 config
패키지 설치
해당 패키지 설치
$ npm install {package_name}
$ npm i {package_name}
의존성 모듈 전체 설치
$ npm install
$ npm i
만약 모든 프로젝트에서 사용할 수 있도록 전역 설치를 하고 싶다면 다음과 같이 -g 옵션
$ npm install -g {package_name}
패키지 삭제
설치 된 패키지를 삭제하는 경우에는 다음과 같이 uninstall
을 사용해서 삭제
$ npm uninstall {package_name}
원래는 패키지를 설치할 때 --save
옵션을 추가해 주면 package.json
의 dependencies
항목에 모듈을 자동으로 추가해 주었는데, npm5 부터는 해당 옵션을 사용하지 않아도 dependencies
에 자동으로 추가된다. 하지만 추가적인 옵션을 통해 dependencies
에 등록하는 방법이 존재한다.
save-prod
:package.json
의dependencies
에 패키지를 등록 (default)save-dev
:package.json
의devDepndencies
에 패키지를 등록save-optional
:package.json
의optionalDependencies
에 패키지를 등록no-save
:dependencies
에 패키지를 등록하지 않음