티스토리 뷰

Mobx를 사용하려고 하던 찰나에 바벨 플러그인으로 @babel/plugin-proposal-class-properties의 loose:true가 사용되는걸 보고 이건 어떤 옵션일까 궁금해서 찾아봤습니다.

 

@babel/plugin-proposal-class-properties이란?

자바스크립트에서도 Class를 사용할 수 있습니다. 하지만, Class내부의 속성들을 선언할때는 바벨 플러그인이 없으면 오류가 납니다.

 

보통은 아래처럼 class의 constructor에서 변수를 초기화 합니다.

/

class Example {
	constructor() {
		this.abc = '123';
	}
}

하지만 아래처럼 쓰고 싶은 경우도 있을겁니다.

 class Bork {
    // 속성 초기화 문법
    instanceProperty = "bork";
    boundFunction = () => {
      return this.instanceProperty;
    };

    // 스태틱 속성
    static staticProperty = "babelIsCool";
    static staticFunction = function() {
      return Bork.staticProperty;
    };
  }

이 플러그인을 사용하면 두가지 케이스를 추가 처리할 수 있습니다.

1. 클래스가 인스턴스화 되면서 속성을 초기화

2. 클래스에 static property를 사용하고 싶을때

 

그럼 loose 옵션은?

아래와 같은 클래스가 있을떄

  class Bork {
    static a = 'foo';
    static b;

    x = 'bar';
    y;
  }

loose: false인 경우

var Bork = function Bork() {
  babelHelpers.classCallCheck(this, Bork);
  Object.defineProperty(this, "x", {
    configurable: true,
    enumerable: true,
    writable: true,
    value: 'bar'
  });
  Object.defineProperty(this, "y", {
    configurable: true,
    enumerable: true,
    writable: true,
    value: void 0
  });
};

Object.defineProperty(Bork, "a", {
  configurable: true,
  enumerable: true,
  writable: true,
  value: 'foo'
});
Object.defineProperty(Bork, "b", {
  configurable: true,
  enumerable: true,
  writable: true,
  value: void 0
});

Object.defineProperty를 통해 클래스의 속성들을 정의해주고 있습니다. 코드가 다소 장황합니다.

loose: true인 경우

var Bork = function Bork() {
  babelHelpers.classCallCheck(this, Bork);
  this.x = 'bar';
  this.y = void 0;
};

Bork.a = 'foo';
Bork.b = void 0;

아래와 같이 할당식 형태로 깔끔하게 변환됩니다. 코드 길이가 매우 줄어들었죠. 코드 길이가 준다는것은 번들 사이즈가 줄어든다는 의미입니다.

댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함