0

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}')
    data

}

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' +
            '\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?

3
  • "let MyClass = eval('class MyClass{}') let myClass = new MyClass": that works? Commented Oct 31, 2021 at 12:16
  • @Andy, yes, that part does work, fixed typos though. Commented Oct 31, 2021 at 12:19
  • better not use eval but return a class from a function like shown below. Commented Oct 31, 2021 at 12:21

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, that's exactly what I needed! Didn't know that syntax, thanks man!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.