NPM에 자주쓰는 함수 배포하기 (TypeScript)
in Daily on Daily
최근에 자주 쓰게 되는 함수가 생겨서 npm에 배포하였습니다.
게시물이나 댓글을 등록한 이후 방금
, 11분 전
, 3시간 전
이렇게 화면에 보여주는 함수를 프로젝트를 진행하면서 사용했는데요.
이후, 스타트업 과제를 진행하면서 다시 한번 쓸일이 생겨서 이참에 NPM에 배포해서 사용해야겠다는 생각이 들어 그 과정을 정리해봅니다.
npm에 배포하는 과정은 생각보다 어렵지 않았습니다.
배포 과정
npm init
npm init
먼저 npm init을 통해 새로운 package.json을 만듭니다.
제가 만든 패키지 예시입니다.
{
"name": "somedaycode-time",
"version": "0.1.0",
"description": "get something useful about time logic",
"main": "/dist/index.js",
"types": "/dist/index.d.ts",
"scripts": {
"build": "rm -rf dist/ && tsc"
},
"repository": {
"type": "git",
"url": "git+https://github.com/somedaycode/somedaycode-time.git"
},
"keywords": ["time"],
"author": "somedaycode <somedaycode@gmail.com>",
"license": "MIT",
"bugs": {
"url": "https://github.com/somedaycode/somedaycode-time/issues"
},
"homepage": "https://github.com/somedaycode/somedaycode-time#readme"
}
- 타입스크립트를 사용한다면 타입스크립트를 설치 후 tsconfig.json을 설정해줍니다.
npm i -D typescript
// tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"declaration": true,
"outDir": "./dist",
"strict": true
},
"exclude": ["node_modules", "dist"]
}
- 필요한 폴더와 파일 생성 (디렉토리 구조 설정)
- 3-1 -
.npmignore
파일을 생성 후 아래와 같이 추가해줍니다.
node_modules/
.gitignore
tsconfig.json
.git
- 3-2 - index.ts 파일을 root에 생성 및 src 폴더 생성
src
- something.ts
.npmignore
index.ts
package.json
package-lock.json
tsconfig.json
- 3-3 - something.ts에 있는 함수를 index.ts에서 export해줍니다.
//index.ts
export { someFunction } from './src/something';
- npm login
로그인 합니다.
npm login
- npm publish
npm run build
npm publish
5번까지 정상적으로 진행이 되었다면 아래와 같이 npm에 나의 패키지가 등록됩니다.
https://www.npmjs.com/package/somedaycode-time