Webpack, Bundler 대체 정체가 뭐야? 왜 쓰는거지? - Webpack 사용해서 Three.js boilerplate 만들기 01

잔잔바리디자이너·2022년 5월 8일
1
post-thumbnail

배경

이전에 three.js 라이브러리를 이용하기 위해서 처음으로 webpack이라는 도구를 접하게 되었는데 당시에는 모듈, 번들러는 물론이고 자바스크립트도 잘 사용하지 못하는 단계였었다. 그래서 boilerplate를 사용해서 웹팩을 사용했지만 이해하지 못한채로 사용해왔다.

최근 다시 three.js 개발 환경을 세팅하기 위해 webpack 없이 세팅하는 방법을 이용해봤는데 왜인지 이럴거면 그냥 Webpack 써서 번들링 하는게 낫겠다 라는 생각이 들어 시작하게 되었다.

🤔webpack이 뭐야?

프로젝트에 사용되는 여러가지 css 파일, 이미지, 모듈 등을 하나의 자바스크립트 파일로 번들링해주는 도구라고 말할 수 있겠다.

참조: webpack 공식 홈페이지

아니 그래서 그게 뭔데;; 왜 쓰는데?

일단 webpack이 뭔지, 왜 사용하는지 알기 위해서 웹팩 없이 Three.js 개발 세팅을 해보겠다.

웹팩 없이 Three 설치, 개발 해보기

  1. 먼저 디렉토리 생성
mkdir manual-three-js
  1. 그리고 해당 디렉토리에서 index.html 파일과 app.js 그리고 style.css 파일을 만들어 준다
touch index.html
touch app.js
touch style.css
  1. html 파일에 css와 js 스크립트 모듈타입으로 연결해준다.
    html 파일:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
  <!-- 모듈 타입으로 지정하는것 잊지말자 !-->
    <script src="app.js" type="module" defer></script>
</body>
</html>
  1. Three 공식 문서에 나와있는것 처럼 CDN을 통해 Three 모듈을 js 파일에 import 해온다. 현재 가장 최근 버전인 0.140.0 버전으로 로드해왔다.
import * as THREE from "https://unpkg.com/three@0.140.0/build/three.module.js"
console.log(THREE)
// live server로 띄워보면 콘솔창에 Three 모듈이 잘 찍히는걸 볼 수 있다.
  1. canvas에 3D 큐브를 띄우는 간단한 예제 작성
/* css 파일 */
*{
    margin:0px;
    padding:0px;
    box-sizing: border-box;
    outline: none;

}

body {
    overflow: hidden;
}
  
canvas {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: black;
  }
// js 파일
import * as THREE from "https://unpkg.com/three@0.140.0/build/three.module.js"
import { OrbitControls } from 'https://cdn.jsdelivr.net/npm/three@0.121.1/examples/jsm/controls/OrbitControls.js';

class App{
    constructor(){
        this.initialize()
        this.render()
        window.addEventListener('resize', () => {
            this.resize()
        })
    }
    initialize(){
        // 렌더러 생성, 캔버스 생성
        this.renderer = new THREE.WebGLRenderer({antialias:true})
        document.body.appendChild( this.renderer.domElement )

        // 씬 생성
        this.scene = new THREE.Scene();

        // 카메라 생성
        this.camera = new THREE.PerspectiveCamera(
            75,
            window.innerWidth/window.innerHeight,
            0.1,
            100
        )
        this.camera.position.z = 3


        // 테스트 오브젝트 생성
        this.cube = new THREE.Mesh(
            new THREE.BoxGeometry(1,1,1),
            new THREE.MeshBasicMaterial()
        )

        // 카메라, 테스트 오브젝트 Scene에 추가
        this.scene.add(this.cube)
        this.scene.add(this.camera)

        // 컨트롤러 추가
        this.control = new OrbitControls(this.camera, this.renderer.domElement)
        this.control.enableDamping = true
    }
    // 애니메이션, 업데이트
    update(){
        this.control.autoRotate = true
        this.control.update()
    }
    // 렌더, 리퀘스트애니메이션프레임으로 재귀호출
    render(){
        this.update()
        this.renderer.setSize(window.innerWidth, window.innerHeight)
        this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
        this.renderer.render(this.scene,this.camera)
        // 화살표 함수로 this 문제 해결
        requestAnimationFrame(()=>{
            this.render()
        })
    }
    resize(){
        this.camera.aspect = window.innerWidth / window.innerHeight
        this.camera.updateProjectionMatrix()
        this.renderer.setSize(window.innerHeight,window.innerHeight)
        this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
    }
}

window.addEventListener('load',()=>{
    const app = new App()
    console.log(app)
})

🟦 결과물:

여기까지 따라왔다면 브라우저에 큐브가 잘 굴러가고 있는게 뜰것이다.

🤔 됐네 그럼 이렇게 개발 하면 되지 뭐하러 webpack을 써?

이 단순한 예제를 위해서도 THREE 모듈, 부가적인 모듈들을 로드해와야한다. 개발자 도구에서 네트워킹 탭을 열어서 한번 소스를 확인해보자.

html 파일, css 파일, js 모듈을 각각 로드해오고 있다. 프로젝트가 커지면서 훨씬 많은 에셋들이 사용될것이고 파일간의 의존성은 더 복잡해질것이다. 결국 더 많은 파일들이 다운로드 될 수록 로딩 시간은 더 길어질것이다!

❌ 문제점:
1. 많은 에셋들을 로드해와야 하기때문에 로딩 시간이 더 길어진다
2. 모듈 파일이 많아도 자바스크립티는 하나의 스크립트로 처리하기때문에 변수 이름간의 충돌같은 문제가 일어날 수 있다.

⭐️ 이러한 문제들을 해결하기 위한 도구

문제들을 해결 해 줄 도구가 바로바로 Bundler 이다.
번들러는 여러가지 서비스가 있지만 webpack이 제일 유명한 번들러이기 때문에 webpack을 사용해보도록 하겠다.


참조
1. webpack이란?
2. three boilerplate
3. three 프로젝트 빌드, 배포 깃헙 구조 참고

쉐이더 작업용 참조
1. 쉐이더 갤러리
2. 소프트바디
3. 행렬으로 지오메트리 구성
4. 소프트바디, 커스텀 버텍스

0개의 댓글