javascript – Using Export Default for Class in LWC

I am new to LWC. If in an interview I am asked, Why do we use export default for class in LWC JavaScript?. What do I answer? Is it done to make the component available for deployment to salesforce? I researched in LWC Basics trailhead and other places but did not find a satisfactory answer. Please help.

Best Answer

This is explained in enough detail here. Here's the core of it:

A module can export a single default function or variable.

// myFunction.js
export default myFunction () { ··· }

The component that imports the function chooses a name to refer to the default export. It doesn't have to be the name of the function or JavaScript file, that’s just a convention.

// consumerComponent.js
import myFunction from 'c/myFunction';

Remember that a class is syntactic sugar for a constructor function so this description is valid in the context of your question.

Note that this page also mentions the use of this syntax:

The export default keywords export a MyComponent class for other components to use.

Finally, the Salesforce's LWC infrastructure must be leveraging the default export from a component JS file to identify the "controller object" to construct when components are referenced from other component templates by name (since that's all you do in order to use them).

Related Topic