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)