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:
npm init vue@latest
- Add Typescript support and keep all other settings as default.
cd vue-project; npm-install
- 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>
- 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}`;
}
npm run build; npm run preview
- Open your browser to
127.0.0.1:4173
and launch the browser's developer tools - 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:
- The error is not present during development (
npm run dev
) but only occurs when previewing the production build. - If you move the
Credentials
class into the script section ofApp.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.