babel/babel

[Bug]: Excessive class properties transformation when other plugins are present

Open

#14.917 aperta il 10 set 2022

Vedi su GitHub
 (11 commenti) (0 reazioni) (0 assegnatari)TypeScript (5826 fork)batch import
Spec: Decorators (Legacy)help wanted

Metriche repository

Star
 (43.894 star)
Metriche merge PR
 (Merge medio 4g 4h) (30 PR mergiate in 30 g)

Descrizione

💻

  • Would you like to work on a fix?

How are you using Babel?

Other (Next.js, Gatsby, vue-cli, ...)

Input code

function log(target, key, desc) {
  return {
    get() {
      let value = desc.get();
      console.log('log: ', key, value);
      return value;
    } 
  }
}
class A {
  @log a = 1;
  
  #privateProperty = 2;
  
  undecoratedProperty = "two";
  
  get #getter() {
    return 3;
  }
  
  get publicGetter() {
    return 'three';
  }
  
  #method() {
    return 4 
  }
  
  publicMethod() {
    return 'four';
  }
}

let a = new A();

console.log(a.a)

Configuration file name

babel.config.cjs

Configuration

'use strict';

const { resolve } = require;

module.exports = {
  presets: ['@babel/preset-typescript'],
  plugins: [
    [
      resolve('@babel/plugin-transform-typescript'),
      {
        allowDeclareFields: true,
        onlyRemoveTypeImports: true,
        // Default enums are IIFEs
        optimizeConstEnums: true,
      },
    ],
    [
      resolve('@babel/plugin-proposal-decorators'),
      {
        // The stage 1 implementation
        version: 'legacy',
      },
    ],
    // I don't want this required
    [resolve("@babel/plugin-proposal-private-methods"), {
      loose: true
    }],
    // Nor this required
    [
      resolve('@babel/plugin-proposal-class-properties'),
      {
        loose: true,
      },
    ],
  ],
};

Current and expected behavior

Current behavior is that without the private methods and class-properties plugins, babel errors, saying I need those plugins.

I would like to omit this plugins as modern browsers support private methods and class-properties -- so I should only need the decorators and typescript plugins.

Environment

This is a closish reproduction on the REPL

But locally, I have

❯ npx envinfo --preset babel

  System:
    OS: Linux 5.15 Ubuntu 22.04.1 LTS 22.04.1 LTS (Jammy Jellyfish)
  Binaries:
    Node: 16.17.0 - ~/.volta/tools/image/node/16.17.0/bin/node
    Yarn: 1.22.19 - ~/.volta/tools/image/yarn/1.22.19/bin/yarn
    npm: 8.19.1 - ~/.volta/tools/image/npm/8.19.1/bin/npm

Possible solution

Remove the requirement for these plugins to exist.

Additional context

I'm a library author, and would like consumers of my library to determine how much babel transformation they wish to do for their supported browsers.

It's possible that if a consumer is only supporting evergreen stuff, my library would need 0 transformation, even with native class fields / methods and private class fields / methods.

Guida contributor