Typescript 언어 기반의 NPM 배포

양치기소년·2023년 9월 9일
0
post-thumbnail

사전 준비

사용자는 NPM에 가입하고 organization과 user를 생성해야 한다.

Nodeenv를 설치한다 (선택)

Python3 & python2 가 설치되어 있어야 한다.

  1. 파이썬을 설치한다.
  2. pip 를 이용하여 nodeenv를 설치한다.
  3. nodeenv가 잘 설치 되었는지 확인한다.

> python -V
> pip install nodeenv
> nodeenv --version

해당 프로젝트에서 nodeenv 설정을 설치한다

해당 프로젝트에 접근할 때 관리자 모드로 접금해야 한다.

> node --version
> nodeenv --node=20.6.1 env-20.6.1

아래와 같이 정상적으로 nodeenv 환경이 설치 되었다.

nodeenv 실행/종료

실행 > .\env-20.6.1\Scripts\activate.bat
종료 > .\env-20.6.1\Scripts\deactivate.bat

Typescript 프로젝트 생성

Node 프로젝트를 생성한다

> npm init --y

Typescript를 설치한다

> npm install --include=dev typescript

Typescript 설정 파일을 생성한다

> npx tsc --init

npx는 패키지의 최신버전으로 설치 및 실행을 시키고 이후에 해당 패키지를 제거하는 방식.

tsconfig.json 파일을 통해 ts 설정

SOURCE CODE
{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig to read more about this file */

    /* Language and Environment */
    "target": "es2016",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */

    /* Modules */
    "module": "commonjs",                                /* Specify what module code is generated. */

    /* Emit */
    "declaration": true,                                 /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
    "declarationMap": true,                              /* Create sourcemaps for d.ts files. */
    "sourceMap": true,                                   /* Create source map files for emitted JavaScript files. */
    "outDir": "./lib",                                   /* Specify an output folder for all emitted files. */

    /* Interop Constraints */
    "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
    "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */

    /* Type Checking */
    "strict": true,                                      /* Enable all strict type-checking options. */

    /* Completeness */
    "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
  },
  "include": [
    "src"
  ],
  "exclude": [
    "env-20.6.1"
  ]
}

TS build 설정

SOURCE CODE
{
  "name": "@oasiscity/oasiscity_typescript_library",
  "version": "1.0.0",
  "description": "",
  "main": "lib/index.js",
  "types": "lib",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "tsc -p ."
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "typescript": "^5.2.2"
  }
}

해당 프로젝트 scope 설정

NPM에 scope이란 같은 패키지 명을 organization으로 차별하여 두는 것.

> npm login --scope=@oasiscity

TS 파일 생성

  1. src/index.ts 파일을 생성한다.
  2. 코드를 입력한다.
  3. npm run build로 통해 파일을 빌드한다.
  4. root에 lib 디렉토리가 생성된다.

const isNumber = (val: unknown): boolean => typeof val === "number";

export {isNumber}

NPM Public Publish로 배포

> npm publish --access public

Jest 설치 (TDD)

> npm install --include=dev jest ts-jest @types/jest

root 디렉토리에 jest.config.js 파일을 생성하고 아래와 같이 등록한다.

SOURCE CODE
module.exports = {
  roots: [
    "./src"
  ],
  testMatch: [
    "**/__tests__/**/*.+(ts|tsx|js)",
    "**/?(*.)+(spec|test).+(ts|tsx|js)"
  ],
  transform: {
    "^.+\\.(ts|tsx)$": ['ts-jest', {
      tsconfig: './tsconfig.json',
    }]
  },
  collectCoverageFrom: [
    "**/*.{js,jsx,ts,tsx}",
    "!**/*.d.ts",
    "!**/node_modules/**",
  ]
}

package.json 파일에서 script부분에 test를 추가한다.

...
"scripts": {
  "test": "jest",
  "build": "tsc -p ."
},
...

테스트 파일을 생성한다

같은 디렉토에 *.test.ts 파일을 생성한다.

SOURCE CODE
import * as LIB from './index'

describe('IsNumber', () => {
  test('Should return true for (1)', () => {
    expect(LIB.isNumber(1)).toBe(true)
  })
  test('Should return false for ("1")', () => {
    expect(LIB.isNumber('1')).toBe(false)
  })
})

테스트 실행

> npm run test

EsLint 설치

> npm install --include=dev eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin

설정 파일을 생성한다

> npx eslint --init

.eslintrc.js 파일이 생성되고 아래와 같이 수정한다.

SOURCE CODE
{
    "env": {
        "browser": true,
        "commonjs": true,
        "es2021": true
    },
    "extends": [
        "eslint:recommended",
        "plugin:@typescript-eslint/recommended"
    ],
    "parser": "@typescript-eslint/parser",
    "parserOptions": {
        "ecmaVersion": 12
    },
    "plugins": [
        "@typescript-eslint"
    ],
    "ignorePatterns": [
        "dist"
    ],
    "rules": {
        "no-console": 2
    }
}

package.json 파일에서 script부분에 lint부분을 추가한다.

...
"scripts": {
  "lint": "eslint ./src --ext .ts",
  "test": "jest",
  "build": "tsc -p ."
},
...
> npm run lint

profile
not a person you are looking for

0개의 댓글