I riffed off this StackOverflow answer and came up with a one-liner that returns the name of the LWC component when deployed to Salesforce. It leverages the fact that JavaScript Error
instances include the name of the file they came from in their stack
property, so you just need the right regular expression to tease out the part you want:
/([^(/]*?)\.js/g.exec(new Error().stack)[1]
Something like this in a LWC called lwcApp
will output "lwcApp" to the console:
import { LightningElement } from "lwc";
export default class LwcApp extends LightningElement {
connectedCallback() {
console.log(/([^(/]*?)\.js/g.exec(new Error().stack)[1]);
}
}
To unpack this:
- When you create a new
Error
instance, it comes with astack
property that looks like this (note the location of "lwcApp"):
Error
at o.connectedCallback (modules/mynamespace/lwcApp.js:4)
at callHook (aura_prod.js:37)
at aura_prod.js:12
at di (aura_prod.js:12)
at Mo (aura_prod.js:12)
...etc...
- The regular expression
/([^(/]*?)\.js/g
looks for text in between a forward slash or open parenthesis and the sequence ".js" and returns it as a capture group. - The
exec
function returns only the first match (conveniently for our purposes here). See MDN docs. exec
's return value is an array where the first item is the entire match and subsequent items are the parenthetical capture groups within the match. We care about the first capture group, hence[1]
.
Hope it helps!