Search code examples
javascriptbabeljs

With Babel, how do I *not* compile away class properties, since browsers support them natively now?


Given this code:

class A {
  #a = 'hi';

  get #b() {
    return 'hello' + this.#a;
  }

  get c() { return this.#b; }
}

I can run this:

let a = new A()
console.log(a.c);

and get hellohi in both Chrome 94 and Firefox 93+ (by just typing it in to the console when the dev-tools are open).

but,

in the babel REPL, I am not able to get the same result.

my browserlist is last 1 firefox versions

Example Babel REPL with the env preset - the output is 31 lines longer, when it shouldn't have changed at all.

Additionally, something interesting:

  • Without the preset:env
  • and then with the decorator line uncommented The output here is suddenly applying all transforms, even though, with my browserlist setting, only the one property should have transforms on it (the one with the decorator). In this example it seems that the class properties transform only supports "all or nothing"? I imagine this has a huge negative impact to build times.

My question is: How do I convince babel to leave properties and methods alone and not transpile them?

According to caniuse.com:


Solution

  • Generally issues with browserslist are due to you not getting the browser versions you expect. It's recommended to update the caniuse database in your project regularly to get latest browser versions for preset-env.

    You can do that like so:

    yarn add -D browserslist@latest
    yarn browserslist --update-db