Search code examples
javascriptecmascript-6es6-moduleswp-calypso

ES6 and "Who imported me"?


I'm working with a javascript system built (I think?) on ES6 compatible javascript that's compiled/transpiled down to browser compatible javascript (Wordpress Calypo, if it matters)

Does modern javascript have a way to reflect into the calling context? Put another way, if I have a javascript module foo

#File: foo/index.js
//...lots of code...
export default () => {
    //...more code...
}

Is there a way to tell, at runtime, which other javascript module and/or file has imported my "foo" module? If this isn't possible, is there a common way to do this with static analysis. If my question doesn't make any sense because I'm made an incorrect assumption (the most likely scenario) , I'd love that assumption corrected.


Solution

  • tl;dr: No and no.

    There's no way for a particular chunk of ES6 Javascript to determine how it was loaded. About the best you can do is have the loading Javascript tell the loaded Javascript how the loader went about it.

    Static analysis can't actually tell you 100% of the time if a particular bit of code will run and therefore can't tell you 100% of the time if a particular file will be loaded. (This is related to the halting problem.) That said, 100% detection is rarely necessary given that file requests are rarely obscured to the degree necessary to hide them. However, I don't know that there is a static analysis tool capable of unwinding the more complex versions of common Javascript loading techniques as usually the code creators already know the circumstances under which they made the code in question load.