Skip to content

[Bug]: Uncaught TypeError: Class constructor cannot be invoked without 'new' #14242

@zhukevgeniy

Description

@zhukevgeniy

💻

  • Would you like to work on a fix?

How are you using Babel?

babel-loader (webpack)

Input code

function customElement(tag: string, options?: ElementDefinitionOptions) {
  return function <T extends CustomElementConstructor>(value: T, { addInitializer }) {
    addInitializer(function (this: T) {
      customElements.define(tag, this, options);
    });
  };
}

function on<K extends keyof HTMLElementEventMap>(type: K, options?: boolean | AddEventListenerOptions) {
  return function <T extends (evt: HTMLElementEventMap[K]) => unknown>(listener: T, { addInitializer }) {
    addInitializer(function <U extends HTMLElement>(this: U) {
      this.addEventListener(type, listener, options);
    });
  };
}

@customElement("example-btn", { extends: "button" })
class ExampleBtn extends HTMLButtonElement {
  @on("click")
  #handleClick(event: MouseEvent) {
    console.log(event);
  }
}

Configuration file name

babel.config.json

Configuration

{
  "presets": ["@babel/preset-env", "@babel/preset-typescript"],
  "plugins": ["macros", ["@babel/plugin-proposal-decorators", { "version": "2021-12" }]]
}

Current and expected behavior

Current behavior:

Uncaught TypeError: Class constructor ExampleBtn cannot be invoked without 'new'
    at Function.<static_initializer> (index.ts?ffb4:18:44)
    at eval (index.ts?ffb4:18:26)
    at Object../src/index.ts (main.js:29:1)
    at __webpack_require__ (main.js:283:33)
    at main.js:1339:37
    at main.js:1341:12

Environment

  • Babel version: 7.17.0
  • Node version: 16.13.1
  • Yarn version: 1.22.17
  • OS: macOS Monterey M1

Possible solution

No response

Additional context

webpack config:

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  mode: "development",

  devtool: "eval-cheap-module-source-map",

  resolve: {
    extensions: [".js", ".ts"],
    modules: [path.resolve(__dirname, "src"), "node_modules"],
  },

  module: {
    rules: [
      {
        test: /\.ts$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: {
            cacheDirectory: true,
            cacheCompression: false,
          },
        },
      },
    ],
  },

  plugins: [new HtmlWebpackPlugin({ template: "./public/index.html" })],
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    Spec: DecoratorsoutdatedA closed issue/PR that is archived due to age. Recommended to make a new issue

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions