What could be causing the "undefined class in the imported eval() function" error

Currently, I'm exploring a unique approach to creating a replacer/reviver combination that facilitates the proper serialization and deserialization of ES6 classes for a TypeScript project I am currently developing.

To accomplish this, I implemented a strategy where I store the class names in the JSON output using a designated key/value pair format (e.g.,

"$className":"Position"
).

While the method worked seamlessly during the initial stages, I encountered a challenge when attempting to instantiate these classes later on. The only solution I found was as follows:

const instance = eval(`new ${className}()`);

During the development process, everything seemed to be functioning correctly within a test file utilizing Vitest. However, upon transferring the code to another file, an error surfaced upon importing the reviver function that utilizes eval():

ReferenceError: Position is not defined

Please note that 'Position' represents an ES6 class in my test file

The tests would pass successfully if I reinserted the reviver code directly into the .test.ts file. Yet, upon removing the code and opting for 'import', it flagged issues with 'Position' being undefined.

I am perplexed about what could potentially be causing this issue. Could it be a limitation inherent to modules? Or perhaps a complexity arising from TypeScript or Vite functionalities impeding hoisting? Potentially, it could relate to some complications tied to the usage of 'eval()' following importation?

Your insight and assistance in navigating through this puzzle would be greatly appreciated.

Edit: Following is the full code extract below. Shifting the content of 'serialization.ts' ahead or behind the class declarations in 'serialization.test.ts' doesn't elicit the 'ReferenceError: Position is not defined' message.

serialization.ts

... (code snippet continues)

serialization.test.ts

... (code snippet continues)

Answer №1

I am perplexed by what could be causing this issue. Is it a common limitation of modules?

Absolutely. The use of the class declaration is limited to the module in which it is defined; it is not accessible globally. This restriction is one of the benefits of modules. Therefore, when Position is declared in serialization.test.ts, the eval call in serialization.ts will not function as expected because Position is out of scope there! To resolve this, you would need to import it, but importing all classes applicable to the serialization library is not practical.

Instead, consider passing the necessary classes, identified by name, as a parameter to the (de)serialization library, for example:

const classes = new Map(Object.entries({
  Position,
  Transform,
}));
const {replacer, reviver} = serialization(classes);

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

Tips for shutting down the pop-up notification with Playwright?

Recently, I delved into the Playwright API and started working on an automation test. The test revolves around logging into a bank account and performing a specific action. However, I encountered a roadblock when a message box popped up on the bank's ...

The API results are able to be displayed in the console, but unfortunately cannot be shown on the user interface. Any efforts to map the results will result in an Un

Can anyone help me troubleshoot an issue with displaying information from a free API on my page? I'm developing a cryptocurrency app using React, and while I can see the array data with console.log(response.data), I encounter an error when I try to se ...

Leveraging jQuery selectors to manipulate data received from an Ajax response

I am encountering an issue with an Ajax call and response. Previously, I had a block of regular javascript code that successfully transformed my select element into a select2 widget. However, when I attempt to convert the select element into a select2 usi ...

What exactly is the purpose of the colon in JavaScript's import statement?

Looking at the following example. import { QueryClientContract, TransactionClientContract } from '@ioc:Adonis/Lucid/Database' I am puzzled by the use of colons and I am unsure about where the imported files are being referenced from. ...

Show dropdown menu on bootstrap responsive table

I've encountered an issue with a bootstrap3 responsive table that includes dropdown selections in each row. When the dropdown is clicked, users have to scroll to view all the options, especially on smaller screens where scrolling becomes impossible. ...

Issue encountered while trying to import firebase-functions-test for testing using mocha

I've been attempting to configure a Firebase Cloud Functions repository for running mocha tests. However, I keep encountering an error when utilizing import * as firebase from "firebase-functions-test"; or const firebase = require("fire ...

Display the Currently Searched Value with Select2

I am currently utilizing the Select2 framework along with an ajax call in my project. I have successfully implemented it, but I am facing an issue where the current search value is being displayed as a selectable option even when there are no search result ...

I am encountering an issue where I am unable to access properties of null while trying to read the 'pulsate' function within the

The current version of my material-ui library is as follows: "@mui/icons-material": "^5.5.1", "@mui/material": "^5.5.1", This is how I included the Button component : import Button from "@mui/material/Button&qu ...

Set up the TempusDominus datetimepicker with the specific configuration provided by the Controller

Incorporating a tempusdominus datetimepicker along with a linked select aspect presents a challenge. After receiving a structure from the controller that comprises a Map>, where dates act as keys enabling the datetimepicker and each date contains an ass ...

The latest version of Chrome is not compatible with jQuery ajax functionality

Greetings, I'm facing a little issue with an ajax request. I'm puzzled why the jQuery ajax method is not functioning properly in the latest version of Chrome ... it works perfectly on Firefox and Opera, but in Chrome, I'm not receiving any r ...

Click a button to adjust the height of an element

My webpage features a dashboard with tabs on the left and corresponding content on the right. To ensure proper alignment, I have utilized Bootstrap to create two columns - one for the tabs and one for the content. However, I am facing an issue where the bo ...

Error message: Unhandled error - $(...).sidr does not exist as a function. [Chrome developer console]

I included this code in the basic module HTML block of a WordPress page builder and encountered the white screen of death. According to the Chrome developer console, the following error occurred: helpers.js?ver=4.5.3:15 Uncaught TypeError: $(...).sidr is ...

Ways to retrieve text like innerText that functions across all web browsers

I need to retrieve the text from a Twitter Follow button, like on https://twitter.com/Google/followers Using document.getElementsByClassName("user-actions-follow-button js-follow-btn follow-button")[0].innerText correctly displays the text as: Follow ...

Utilizing emailyak to send an email within an AngularJS function

After creating an emailyak account, I attempted to send an email using a JavaScript function. While I was able to successfully send an email with a curl command, I encountered difficulties when trying to replicate the same function in JavaScript. Here is ...

New to React and looking for guidance on implementing .forEach or .includes in my code

My task involves going through an array and checking if a string that the user inputs into the form exists in it. This can be achieved using forEach or .includes method. I am basically trying to filter out the array based on the input. If someone could de ...

Can you provide guidance on how to format index signatures for objects in TypeScript

Currently, I am utilizing TypeScript in conjunction with Angular 1.5 and the Angular 1.5 type definition file. However, I am facing a challenge in defining the bindings within an Angular component. Within the definition file, the bindings are defined as f ...

Exploring strategies for connecting React components with two distinct sources of information

Greetings! I am looking to display information about schools and also include images of the schools or programs. I have separate URLs for images and information stored in different states, with images saved on S3 and information in PostgreSQL. This has le ...

I am experiencing difficulty with implementing a page break within the <tr> and <tbody> elements

Below is the code I am working with: {% for item in child.items %} {%set ns.count = ns.count + 1%} <tbody style="page-break-inside: avoid"> <tr style="page-break-inside: avoid"> ...

Check all references in the array within the specified relational column on Parse.com

In my Conversation classes, there is a members relation attribute that points to the User class. The members attribute contains the people who belong to a specific conversation. I am trying to query whether a given array of User pointers is part of a par ...

Using JavaScript to insert a value through AJAX

I'm currently working on a website that displays the value of a .TXT file, and here is the progress I've made so far: <script> $(document).ready(function() { $("#responsecontainer").load("info.txt"); var refreshId = setInterval(function( ...