👨‍💻 javascript

WebGPU + Typescript 설정하기

읏차 2024. 8. 11. 18:19

기존에는 react나 next 프로젝트에 typescript를 사용했을 때는 프로젝트를 생성했을때 typescript 옵션을 추가해줬기 때문에 관련 설정을 하는데 특별한 어려움이 없었다.

 

이번에 WebGPU를 공부하기 시작하면서 기본적인 typescript 설정에도 어려움을 겪어 간단히 정리하였다.

 

https://webgpufundamentals.org/webgpu/lessons/ko/webgpu-fundamentals.html

 

WebGPU 기초

WebGPU의 기초

webgpufundamentals.org

 

해당 사이트에 있는 sample code가 js로 되어 있어 이를 ts로 변환하기로 했다.

 

1. 간단한 html 생성

2. webgpu sample code(.js)를 .ts파일로 변경

3. 실행해보기

4. 안됨

 

먼저 webgpu에서 typescript를 사용하기 위해서는 몇 가지 패키지를 설치해줘야 한다.

npm install --save-dev @webgpu/types
npm install --save-dev typescript

 

 

추가로 html 파일 실행을 위해 http-server를 설치해줬다.

npm install --save-dev http-server

 

 

typescript를 브라우저에서 실행하려면 javascript로 변환한 이후 변환된 js파일을 html의 script 태그에 추가해줘야 한다.

<script src="./dist/main.js"></script>

 

typescript를 javascript로 변환하는 가장 간단한 방법은 tsc(typescript compiler)를 사용하는 방법이다.

tsc main.ts --outFile dist/main.js

 

해당 명령어를 실행하면 다음과 같은 에러를 만날 수 있다. 

 

다양한 에러가 떳지만 가장 많은 이유는 webgpu/types에 정의된 type을 tsc가 모르기 때문이다.

 

여기서 우리가 이전에 자주 설정했었던 tsconfig.json 파일을 사용해서 ts파일을 js로 변환해주면 된다.

// tsconfig.json

{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "module": "ESNext",
    "lib": ["ES2020", "DOM"],
    "esModuleInterop": true,
    "strict": true,
    "skipLibCheck": true,
    "removeComments": true, // 주석 제거
    "downlevelIteration": true, // 비동기 반복문 지원
    "sourceMap": true, // 소스 맵 생성

    /* types */
    "typeRoots": ["./node_modules/@types", "./node_modules/@webgpu/types"],
    "outDir": "./dist"
  }
}

 

tsconfig.json파일에서 tsc의 다양한 설정을 프로젝트 별로 유지하기 위해서 사용한다.

typeRoots 속성에서 webgpu/types를 추가해주면 tsc가 사용할 수 있는 type이 있는 위치를 알려준다.

 

// package.json

{
  "scripts": {
    "build": "tsc --project tsconfig.json",
    "start": "http-server -p 8080 -o"
  },
  "devDependencies": {
    "@webgpu/types": "^0.1.44",
    "http-server": "^14.1.1",
    "typescript": "^5.5.4"
  }
}

 

tsc --project tsconfig.json을 사용하면 프로젝트 전체의 ts 파일을 tsconfig.json의 설정을 사용하여 js 파일로 바꿔준다.

이 경로 또한 tsconfig.json의 include와 exclude 속성으로 변경가능하다.

그리고 node_modules 하위 파일은 기본적으로 무시된다.