Create class declaration programmatically in javascript?

Eventually what I need is to build a class declaration at runtime providing dynamic parameters to a property annotation:

import {Type} from "external-module";

export default class TypeWrapper {

    @Type(() => '{this part of the class declaration should be changable at runtime}')


I have a feeling that this should be possible to achieve but can’t figure out a proper way yet.

As a proof of concept I was trying to do something like below:

let MyClass = eval('(class MyClass{})')
let myClass = new MyClass()

That works, however MyClass needs to define some imports:

        let MyClass = eval('import {Type} from "external-module"' +
            '(class MyClass{})')

That one fails with “Cannot use import statement outside a module” which is quite expected.

Another approach I tried is to load a module from string:

        var moduleData = '' +
            'import module from "./module/path/file.js"n' +
            'n' +
            'export default class MyClass {n' +
            '}n' +
        var b64moduleData = "data:text/javascript;base64," + btoa(moduleData);

        let MyClass = await import(b64moduleData)

But it fails with “Cannot find module“, suggesting it assumes b64moduleData is a path rather than module data itself.

Anyone has any suggestions?


Normally, for this type of thing I would use a class factory:

import { Type } from 'some-module';

function createClass(parameters) {
  return class {

const MyClass = createClass(...);

I’m unsure if this fits your particular use case based on the details provided.

EDIT: As a side-note, as far as I know, you cannot construct modules from a string, which is what your code is doing, and what the compiler is complaining about.