본문으로 바로가기

TIL 2022-02-03 JS ErrorHandling, svgr, babel-loader vs ts-loader

category TIL 2022. 2. 3. 22:02
Error

Error 객체의 종류로는 일반적인 Error 객체 제외하고도

  • EvalError
  • InternalError
  • RangeError
  • ReferenceError
  • SyntaxError
  • TypeError
  • URIError

등이 있고 커스텀 객체를 만들수도 있다.

 

먼저 일반적인 Error 객체의 속성을 알아보자면

 

prototype으로 message, name, fileName, lineNumber, columnNumber, stack이 있는데,

 

name은 에러의 이름, EvalError면 EvalError, TypeError면 TypeError, 즉 에러 종류의 이름을 의미하고 message는 Error의 메세지로 대체로 throw할때 넣는 내용이 메시지다.

 

try {
  throw new Error("이런!");
} catch (e) {
  alert(e.name + ": " + e.message);
}

이렇게 try catch로 잡아줄수 있으며, 결과값으로는 Error: 이런! 이 나올 것을 알 수 있다.

 

커스텀 에러는

 

class CustomError extends Error {
  constructor(message) {
    super(message)
    this.name = 'CustomError'
  }

  toString() {
    return this.name + ': ' + this.message
  }
}

throw new CustomError('Emit CustomError')

class 객체를 이용하여 간결하게 만들어 줄 수 있다.

 

여담으로 Typescript에서 catch에서 받는 인자로써의 e는 unknown로 type되어있고 (4.4이상)

try {
  throw new Error('foo');
} catch (err: unknown) {
  if (err instanceof Error) {
    return {
      message: `Things exploded (${err.message})`,
    };
  }
}

instanceof 를 통해서 type를 확정지어줄수 있다.

 

이전까지는 e의 타입은 any였는데 그러다보니 존재하지 않는 e.helloeveryone 등의 없는 속성들을 사용해도 TS Error가 발생하지 않았기에 바꾼 것이다.

 

 

svgr

svgr은 SVG를 React Component로 변환시켜주는 도구다.

 

리액트에서 SVG를 사용하는 방법으로는 크게 3가지 정도가 떠오르는데,

 

첫번쨰는 그냥 컴포넌트에 인라인으로 SVG를 삽입하는 것이고,

두번쨰는 Img 태그의 url에 svg 파일 주소를 넣어서 해결하는 것이고,

세번째는 별도의 컴포넌트를 생성하는 것이다.

 

1은 제일 쉽지만 지저분하고 재사용성도 떨어지고

2는 SVG의 스타일링이 까다로우며

3은 제일 쓰기 편하지만 매 SVG마다 컴포넌트를 작성하는 것은 너무나 귀찮은 짓이다.

 

이를 자동화해주는 것이 웹팩에서 svgr를 사용하는 것이다.

 

사용방법은 간단한데,

module.exports = {
  module: {
    rules: [
      {
        test: /\.svg$/i,
        issuer: /\.[jt]sx?$/,
        use: ['@svgr/webpack'],
      },
    ],
  },
}

이렇게 .svg파일에 svgr를 사용하도록 웹팩에서 처리해주면

import Star from './star.svg'

const Example = () => (
  <div>
    <Star />
  </div>
)

바로 컴포넌트처럼 사용할 수 있다.

https://react-svgr.com/docs/webpack/

 

SVGR - Transforms SVG into React Components. - SVGR

Transforms SVG into React Components.

react-svgr.com

 

babel-loader와 ts-loader

개발환경을 세팅하면서 babel-loader와 ts-loader의 차이점, 그리고 뭐가 더 좋은지에 대해서 궁금해졌다.

babel-loader에서도 @babel/preset-typescript를 통해서 타입스크립트를 컴파일할 수 있기 때문이다.

 

이 둘의 차이점으론

 

babel-loader는 타입 체킹을 다 버리고 js로만 변환하기 때문에 빠르다

ts-loader는 타입체킹을 하기 떄문에 느리다.(fork-ts-checker-webpack-plugin 쓰면 어느정도 해결 가능)

 

다만 babel-loader 같은 경우에는 폴리필 기능이 있고 ts-loader는 없다.

 

Typescript 공식 Example에서는 ts-loader와 babel-loader을 둘다 사용한다.

 

https://github.com/microsoft/TypeScriptSamples/blob/master/react-flux-babel-karma/webpack.config.js

 

GitHub - microsoft/TypeScriptSamples: Community Driven Samples for TypeScript

Community Driven Samples for TypeScript. Contribute to microsoft/TypeScriptSamples development by creating an account on GitHub.

github.com