1

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

Stefan
  • 10,010
  • 7
  • 61
  • 117
  • check out [source maps](https://developer.mozilla.org/en-US/docs/Tools/Debugger/How_to/Use_a_source_map) – Thomas Apr 18 '19 at 14:04
  • Just in case you don't already know, it can save some headaches to realize that JS doesn't actually have "classes" -- despite the `class` keyword and related syntax. (MDN explains: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain). – Cat Apr 18 '19 at 14:13

2 Answers2

1

document.currentScript works in all browser except IE. You can use it like this:

var script = document.currentScript;
var fullUrl = script.src;
MauriceNino
  • 6,214
  • 1
  • 23
  • 60
0

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

Stefan
  • 10,010
  • 7
  • 61
  • 117