NPM에 패키지 배포하고 사용해보기 (+ 타입스크립트)
- NPM에서 라이브러리를 설치받는 일은 매우 빈번했지만, 내가 실제로 NPM에 라이브러리를 배포하는 경험은 없었다.
- NPM은 개인이나 팀으로 유료 요금제도 제공하여 private하게 패키지를 관리할 수 있는 기능도 제공하고 있기에, 앞으로 사용할 일이 있을 것이라 생각하고 이번에 테스트로 배포를 진행해보았다.
npm
Bring the best of open source to you, your team, and your company Relied upon by more than 11 million developers worldwide, npm is committed to making JavaScript development elegant, productive, and safe. The free npm Registry has become the center of Java
www.npmjs.com
- 우선 npm 아이디가 필요하다.
- 회원가입을 한다.
- 그리고 배포할 패키지의 프로젝트로 이동한다.
- npm login로 로그인을 한다.
- npm publish를 입력하면 배포가 시작된다.
- 첫 배포시에는 이메일을 입력해야 한다.
- package.json에는 name, version, main 값이 반드시 필요하다.
- 만약 수정사항이 있다면, package.json에서 version값을 올리고 다시 npm publish를 한다.
다음은 내가 실제 배포한 패키지이다.
https://www.npmjs.com/package/colors-helper-tools
colors-helper-tools
help use color style ✨. Latest version: 1.8.0, last published: 3 months ago. Start using colors-helper-tools in your project by running `npm i colors-helper-tools`. There are no other projects in the npm registry using colors-helper-tools.
www.npmjs.com
🍬 만약 타입스크립트로 작성한 모듈을 배포할 때, package.json은 다음과 같이 작성할 수 있다.
{
"name": "name",
"version": "1.0.0",
"description": "citron03",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "tsc",
"start": "node ./dist/index.js",
"dev": "ts-node ./dist/index.ts"
},
"keywords": [
"package",
],
"engines": {
"node": ">=14"
},
"author": "",
"license": "ISC",
"dependencies": {
},
"devDependencies": {
"ts-node": "^10.9.1",
"typescript": "^4.9.5"
}
}
- 모듈의 시작점인 main은 tsc를 통해서 빌드된 js 파일로 설정한다.
- 그리고 types에 d.ts 파일을 설정해주면, npm에서 TS를 내장한 모듈로 인식된다.
- tsc가 실행될 때 d.ts 파일을 자동으로 생성될 수 있도록 tsconfig.json을 다음과 같이 수정한다.
{
"include": ["src"],
"exclude": ["node_modules"],
"compilerOptions": {
"outDir": "dist",
"target": "ES6",
"rootDir": "src",
"lib": ["ES6"],
"strict": true,
"esModuleInterop": true,
"module": "CommonJS",
"declaration": true
}
}
추가해야될 옵션은 compilerOptions의 declaration로, 기본값이 false로 설정되어 있다.
true로 설정해주면, 타입스크립트 컴파일러가 실행될 때, 자동으로 각 소스파일에 대한 .d.ts 타입 파일이 생성된다.
.npmignore 파일에 npm에 배포하지 않을 파일과 폴더를 쓸 수 있다. 작성법은 .gitignore와 같은데, 만약 .npmignore 파일이 없다면 .gitignore가 그 역할을 대신한다.
즉, .npmignore 파일이 없을 땐 .gitignore에 적힌 파일과 폴더들이 배포 시 포함이 되지 않는다.
배포한 모듈을 받아 require가 아닌 import로 불러온다면, 다음과 같은 에러가 발생한다.
(node:80396) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
에러 메세지를 따라 package.json의 type을 module로 설정하거나, 확장자를 .mjs로 변경하면 된다.