2

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.

6

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).

  • 2
    You may like to add some details here in your answer from the link, as links could potentially break in future. – Jayant Das Nov 8 at 14:43
  • Fair point. The core piece added. – Phil W Nov 8 at 15:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.