Webpack, TypeScript를 이용한 웹페이지 개발 설정

기본 설정

# Node.js 설치

npm 명령 실행을 위함

# npm init -y

npm init는 package.json을 만들기 위한 명령이고 -y를 붙임으로써 별도의 입력 없이 기본 값으로 진행 시킴. package.json은 작성하고자 하는 프로젝트에 대한 설정 파일로 볼 수 있으며, 프로젝트 이름과 버전 등과 같은 설명과 프로젝트가 사용하는 라이브러리에 대한 정보 그리고 프로젝트 실행 등을 위한 명령에 대한 정보가 담겨있음. package.json 파일은 npm을 위한 파일임(VS.Code를 위한 것이 아님)

# npm install webpack webpack-cli --save-dev

# npm install typescript ts-loader --save-dev

# tsconfig.json 파일 생성 및 내용 작성

{
    "compilerOptions": {
        "outDir": "./dist/",
        "sourceMap": true,
        "noImplicitAny": true,
        "module": "es6",
        "target": "es5",
        "allowJs": true
    }
}

# webpack.config.js 파일 생성 및 내용 작성

const path = require("path");

module.exports = {
    mode: "development",
    entry: "./src/index.ts",
    devtool: "inline-source-map",
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                use: "ts-loader",
                exclude: /node_modules/,
            },
        ],
    },
    resolve: {
        extensions: [".tsx", ".ts", ".js"],
    },
    output: {
        filename: "bundle.js",
        path: path.resolve(__dirname, "dist"),
    },
}

# src, dist 폴더 및 index.html(dist 폴더), index.ts(src 폴더) 파일 생성

# index.html 코드 입력

...

<script src="bundle.js"></script> 

...

# index.ts 코드 입력

console.log("Hello");

# package.json 파일의 “scripts” 파트에 “bundle”: “webpack” 입력

{
  ..
  "scripts": {
    ..
    "bundle": "webpack"
  },
  ..
}

# npm run bundle 실행

Typescript로 작성된 파일을 Javascript 파일로 트랜스파일링 시킴

자동 실행을 위한 설정

# package.json 파일의 “scripts” 파트에 “watch”: “webpack –watch” 및 “start”: “npm run bundle && npm run watch” 추가

{
  ..
  "scripts": {
    ..
    "bundle": "webpack",
    "watch": "webpack --watch",
    "start": "npm run bundle && npm run watch"
  },
  ..
}

# VS.Code에서 Live Server 확장 기능 설치

# npm start 실행

이제부터 Typescript로 작성된 파일을 수정하면 Javascript 파일로 지동으로 트랜스파일링 시킴

# index.html 열고 GO LIVE 활성화

브레이크 디버깅

# VS.Code의 “실행 및 디버그” 클릭을 통해 launch.json을 생성 (크롬 선택)

# launch.json 파일에서 “url”의 값을 “http://127.0.0.1:5500/dist”으로 수정

{
    ..
    "configurations": [
        {
            ..
            "url": "http://127.0.0.1:5500/dist",
            ..
        }
    ]
}

babylonjs 라이브러리 설치

# npm install @babylonjs/core

# tsconfig.json에 “moduleResolution”: “node” 추가

{
    "compilerOptions": {
       ..
       "moduleResolution": "node"
    }
}

위의 설정을 입력해야 babylonjs 모듈을 import할 때(예: import { Scene } from “@babylonjs/core”) 문제가 없음

최종 설정 파일 내용

# tsfonfig.json

{
    "compilerOptions": {
        "outDir": "./dist/",
        "sourceMap": true,
        "noImplicitAny": true,
        "module": "es6",
        "target": "es5",
        "allowJs": true,

        "moduleResolution": "node"
    }
}

# webpack.config.js

const path = require("path");

module.exports = {
    mode: "development",
    entry: "./src/index.ts",
    devtool: "inline-source-map",
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                use: "ts-loader",
                exclude: /node_modules/
            },
        ],
    },
    resolve: {
        extensions: [".tsx", ".ts", ".js"],
    },
    output: {
        filename: "bundle.js",
        path: path.resolve(__dirname, "dist"),
    },
}

# package.json

{
  "name": "tstbabylonjs_ts",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "bundle": "webpack",
    "watch": "webpack --watch",
    "start": "npm run bundle && npm run watch"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "ts-loader": "^9.4.1",
    "typescript": "^4.8.4",
    "webpack": "^5.74.0",
    "webpack-cli": "^4.10.0"
  },
  "dependencies": {
    "@babylonjs/core": "^5.26.1"
  }
}

# launch.json

{
    // IntelliSense를 사용하여 가능한 특성에 대해 알아보세요.
    // 기존 특성에 대한 설명을 보려면 가리킵니다.
    // 자세한 내용을 보려면 https://go.microsoft.com/fwlink/?linkid=830387을(를) 방문하세요.
    "version": "0.2.0",
    "configurations": [
        {
            "type": "chrome",
            "request": "launch",
            "name": "Launch Chrome against localhost",
            "url": "http://127.0.0.1:5500/dist",
            "webRoot": "${workspaceFolder}"
        }
    ]
}

Javascript, 전화번호 형식으로 변경하는 함수

사용자가 원하는 형식으로 전화를 입력했을때 정해진 형식(xx-xxx-xxxx)으로 변경해주는 함수입니다.

const formatPhoneNumber = (input) => {
    const cleanInput = input.replaceAll(/[^0-9]/g, "");
    let result = "";
    const length = cleanInput.length;

    if(length === 8) {
        result = cleanInput.replace(/(\d{4})(\d{4})/, '$1-$2');
    } else if(cleanInput.startsWith("02") && (length === 9 || length === 10)) {
        result = cleanInput.replace(/(\d{2})(\d{3,4})(\d{4})/, '$1-$2-$3');
    } else if(!cleanInput.startsWith("02") && (length === 10 || length === 11)) {
        result = cleanInput.replace(/(\d{3})(\d{3,4})(\d{4})/, '$1-$2-$3');
    } else {
        result = undefined;
    }

    console.log(`${input} -> ${result}`);

    return result;
}

테스트를 위해 다음 코드를 실행해 보면..

formatPhoneNumber("08032332333");
formatPhoneNumber("021231234");
formatPhoneNumber("(02)12351234");
formatPhoneNumber("63633221");
formatPhoneNumber("010-9543-3224");
formatPhoneNumber("0625252312");
formatPhoneNumber("03112341234");

결과는 다음과 같습니다.

021231234 -> 02-123-1234
08032332333 -> 080-3233-2333
021231234 -> 02-123-1234
(02)12351234 -> 02-1235-1234
63633221 -> 6363-3221
010-9543-3224 -> 010-9543-3224
0625252312 -> 062-525-2312
03112341234 -> 031-1234-1234

인지하지 못한 전화번호 형식이 있을 수 있으니 개선해서 사용하시면 됩니다.