Error: The class constructor [] must be called with the 'new' keyword when creating instances in a Vite project

I encountered an issue in my small Vue 3 project set up with Vite where I received the error message

Class constructor XX cannot be invoked without 'new'
. After researching online, it seems that this problem typically arises when a transpiled class extends a native class, although I do not have any such constructs in my code. Unfortunately, I lack the fluency in Javascript/Typescript/transpilation/ESXXXX to identify the root cause.

To illustrate the problem, below is a minimal configuration:

  1. npm init vue@latest
  2. Add Typescript support and keep all other settings as default.
  3. cd vue-project; npm-install
  4. Replace the contents of App.vue with the following:
<script setup lang="ts">
import { Credentials } from './creds'

function logIn( creds: Credentials ) {
  // perform login actions here
}
</script>

<template>
  <button @click="logIn(new Credentials( 'aaa', 'bbb' ))">CLICK ME</button>
</template>
  1. Create a new file, creds.ts, with the following content:
export class Credentials {
  constructor(
    public readonly username: string,
    public readonly password: string
  ) {}
  toString = (): string => `${this.username}:${this.password}`;
}
  1. npm run build; npm run preview
  2. Open your browser to 127.0.0.1:4173 and launch the browser's developer tools
  3. Click the button and check the javascript console for the error:
    index.b42911a0.js:1 TypeError: Class constructor XX cannot be invoked without 'new'

A couple of odd observations:

  1. The error is not present during development (npm run dev) but only occurs when previewing the production build.
  2. If you move the Credentials class into the script section of App.vue, the error no longer appears in the production build.

What is causing this mysterious error when instantiating a class from a separate file within an event handler during production?

EDIT 2: Previous irrelevant information has been removed.

Answer №1

In the month of October 2023, I encountered a challenging issue while working with Vue 3 and the composition API. After some investigation, I discovered that attempting to assign an object instance or similar directly within a tag would result in an error.

During development, this issue may not be immediately apparent, but when running the application in preview mode, the error becomes evident.

The workaround involves creating a function where you can perform any necessary operations instead of directly assigning values.

Below is an example of a CRUD filter that I developed and wanted to share. When clicking on the "clear" button that invokes the "clear" method, everything functions correctly. However, clicking on the "clear" button that assigns the variable directly within the event handler will trigger an error in production.

<div class="row container-button">
    <span class="col-md-2">
      <button
        id="btn-filter"
        class="btn btn-primary btn-sm"
        @click="emits('filter', item)"
      >
        Filter
      </button>
      
      <!-- The following approach works without issues -->
      <button id="btn-clear" class="btn btn-secondary btn-sm" @click="clear"> Clear </button>
      
      <!-- Using this method leads to errors in a production environment! -->
      <button id="btn-clear" class="btn btn-secondary btn-sm" @click="(() => filter = new QueryFilter())"> Clear </button>
    </span>
</div>

<script setup lang="ts">
let filter = ref<QueryFilter>(
  new QueryFilter()
);

const emits = defineEmits<{
  (event: "filter", value: any): QueryFilter;
}>();

function clear(){
  filter.value = new QueryFilter()
}
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Animate the smooth transition of a CSS element when it is displayed as a block using JQuery for a

I have implemented the collapsible sections code from W3 School successfully on my website. Now, I am trying to achieve a specific functionality where the "Open Section 1 Button" should slide down with a margin-top of 10px only if the first section "Open S ...

Setting up Webpack for my typescript React project using Webpack Version 4.39.2

I have been given the task of fixing the Webpack build in a project that I am currently working on. Despite not being an expert in Webpack, I am facing difficulties trying to make it work. The project has an unconventional react frontend with typescript. I ...

Trouble with Bootstrap popover displaying content

I've been working on implementing the bootstrap popover feature on a website and have had some success. I managed to get the popover to appear when the link is clicked, but unfortunately, I'm not seeing any content in the box other than the title ...

How to transform an array into a collection of objects using React

In my React project, I encountered the following data structure (object of objects with keys): const listItems = { 1:{ id: 1, depth: 0, children: [2,5] }, 2:{ id: 2, depth: 1, children: [3,4], parentIndex: 1, disable ...

Using string interpolation within the onclick event (Ionic 2 + Angular 2)

One question that's troubling me - I'm attempting to pass a string within an "onclick" event in my Ionic 2 app, but it keeps throwing an error. <button onclick="window.plugins.socialsharing.shareViaWhatsApp(null, null, '{{sound.file}}&a ...

The complexity of JQuery's design has left many puzzled

I am new to using Jquery and I have come to the following realizations: Every selector in Jquery always returns a wrapped list of items, which can be: An empty list A list with a single element A list with multiple elements Chained functions operate o ...

Limit the range of potential inputs for the function parameter

class Coordinate { constructor(readonly x: number, readonly y: number) {} } const Up = new Coordinate(0, -1); const Right = new Coordinate(1, 0); const Down = new Coordinate(0, 1); const Left = new Coordinate(-1, 0); // How can we restrict the directio ...

Stretching the Mantine Accordion Section

The Mantine accordion requires that its content be of type Accordion.Item, as indicated in the documentation for the children props. This means that even functions returning AccordionItem will not be recognized. Therefore, only AccordionItem(s) created in ...

"Browser compatibility issues: 404 error on post request in Firefox, while request is

When following this tutorial on React and PostgreSQL, the app should display the JSON fetch in the bash terminal around the 37-minute mark. However, there seems to be a problem as there is no feedback showing up on the npm or nodemon servers. After tryin ...

EJS unable to display template content

I am having an issue with rendering a template that contains the following code block: <% if(type === 'Not Within Specifications'){ %> <% if(Length !== undefined) { %><h5>Length: <%= Length %> </h5> <% ...

Dealing with transformed data in AngularJS: Best practices

Scenario I have a dataset structured like: [{ xRatio: 0.2, yRatio: 0.1, value: 15 }, { xRatio: 0.6, yRatio: -0.3, value: 8 }] I need to convert this data into absolute values for display in a ng-repeat. However, when I attempt to do so usin ...

What is the best way to transform an HTML <script> tag into React code?

I am new to the world of JavaScript and React. Can someone help me convert the script below into a React component? <div id="SOHUCS" sid="xxx"></div> <script charset="utf-8" type="text/javascript" sr ...

The variable "tankperson" is not recognized

While attempting to run an AJAX request upon page load, I encountered a particular error even though I have ensured that all the necessary libraries are included. The variable tankperson is derived from $_GET['name'] An unhandled ReferenceErr ...

What could be causing the multifiles uploader to fail in uploading files?

I have been attempting to create a multiple files uploader with sorter connected to a database on my website. However, whenever I try to upload some files, the uploader sends me several notices. Notice: Undefined index: media in /var/www/mediasorter/mediau ...

What is the best way to combine the existing array data with the previous array data in JavaScript?

I am implementing server-side pagination in my MERN project. Let's say I retrieve 100 products from the database and want to display only 30 products, with 10 products per page. When a user navigates to the 4th page, I need to make another API call to ...

Enhancing Skylinkjs functionality using Typescript

Hello fellow developers, I am new to using typescript and currently experimenting with incorporating SkylinkJS into my project. Can anyone guide me on the best practices for utilizing an npm library with TypeScript? If you are interested in checking out t ...

Load prior state when the value changes with UseState in NextJS

In the development of my e-commerce application, I am currently working on implementing filters based on category and price for the Shop page. To handle this functionality, I have established the initial state as follows: const [filters, setFilters] = useS ...

How can I use VB codebehind in ASP to display a dialog box to the user asking for a yes or no response?

I am faced with a scenario where a user has chosen a product, the system has retrieved the product record, and the backorder flag has been set. I need to inquire if the user still wants to proceed with including the product in the order. However, I am stru ...

New update in Fullcalendar v2: Enhancements to dayRender function for agenda view and agenda

For the newest version of FullCalendar, I am in need of the dayRender callback to modify the color of disabled days. Unfortunately, this specific callback only functions for month, basicWeek, and basicDay views. However, I require this functionality for a ...

Creating a dynamic cascading dropdown list with Vue.js: Step-by-step guide

I successfully implemented a dropdown list using Vue.js, but now I want to add another similar list. How can I set this up? Here are the codes for both dropdown lists: var addUserVue = new Vue({ el: "#app", data: { heading: "Vue Select Cas ...