Can an LWC component get its own name?
Either you can directly get info from this.template.host
:
// testComponent.js
connectedCallback() {
console.log(
this.template.host.localName // c-test-component
.split('-') // ['c', 'test', 'component']
.slice(1) // removes ns prefix => ['test', 'component']
.reduce((a, b) => a + b.charAt(0).toUpperCase() + b.slice(1)) // converts to camelCase => testComponent
);
}
Element.localName
read-only property returns the local part of the qualified name of an element.
Having the local name of the component (e.g. c-test-component
) we can process it to get get rid of the namespace prefix and to convert the dash-separated
string to camelCase
.
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". - 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!