Search code examples
javascriptreflectioncode-generationclassloading

How to get source code location from ES6 JavaScript class instance?


I would like to generate some code from my object tree. In order to generate the required import statements, I need to find out the source code location for a given class from a class instance.

I am already able to get the expected name MyClass with

var name = instance.constructor.name;

but not the source code location

'/src/package/myClass.js'

=>How to do so?

For Java it would work like described here:

Find where java class is loaded from

If I inspect the constructor in Chrome developer tools with dir(constructor), I can see some property

[[FunctionLocation]]: myClass.js:3

and if I hover over it, I can see the wanted path. How can I get that property programmatically?

enter image description here

Edit

Just found that [[FunctionLocation]] is not accessible:

Access function location programmatically


Solution

  • A possible work around seems to be to call

    determineImportLocation(){
        var stack = new Error().stack;
        var lastLine = stack.split('\n').pop();
        var startIndex = lastLine.indexOf('/src/');
        var endIndex = lastLine.indexOf('.js:') + 3;
        return '.' + lastLine.substring(startIndex, endIndex);
    }
    

    in the constructor of MyClass and store it for later access:

    constructor(name){
        this.name = name;
        if(!this.constructor.importLocation){
            this.constructor.importLocation = this.determineImportLocation();
        }                       
    }
    

    That would however require to modify all classes that I would like to import. Please let me know if there is a solution that does not require to modify the class itself.

    enter image description here