6

Below is my JS code in LWC:

import searchBears from '@salesforce/apex/BearController.searchBears';
import { LightningElement, wire } from 'lwc';

I would like to understand why some import statements are having curly braces and some are not. I tried to refer to the document but not succeeded.

3 Answers 3

6

It depends on whether the export function is written as default or named exports. I suggest doing a read on default vs named exports on MDN here

Suggest also reading this answer to understand in depth.

An example that does not curly bracket will be as below

class Myclass {...};
export default Myclass;

The import statement would be as below

import Myclass from './src/index.js'

With curly braces

class Myclass {...};
export Myclass;

The import would be as below

import {Myclass} from './src/index.js'

If you view your type definition (under .sfdx/typings/lwc/apex folder ) in your vscode you should see something like below where you see export default statement

enter image description here

1
  • Thanks Mohith for the description. It's really helpful. Commented Jun 17, 2020 at 2:56
5

If you are using the default export, you must not use curly braces. If you are not using the default export, you must use curly braces. They are not optional, but instead reflect if you are importing the default export or not. For example, the following is invalid:

import { myMethod } from '@salesforce/apex/MyClass.myMethod';

As well as:

import LightningElement from 'lwc';

Both will result in errors. You must consult the documentation or source code (for custom exports) to determine if curly braces are required or restricted.

2
  • The other alternative is typings file under the vscode typings folder under .sfdx folder Commented Jun 17, 2020 at 2:59
  • Thanks sfdcfox for the description. It's really helpful. Commented Jun 17, 2020 at 3:04
4

If a default export is used in the class you want to access, eg

export default yourthing

Then you don't need braces.

If the ES6 export is explicit, you do.

An explicit export looks like:

function add( a, b ) {
  return a + b;
}
function sayhi( name ){
  return `Hi ${name}`;
}
export { add, sayhi };

In this case, you would need to import these like:

import { add, sayhi } from '/mymodule';

Or if you only wanted part of the code:

import { add } from '/mymodule'
1
  • Thanks Caspar for the description. It's really helpful. Commented Jun 17, 2020 at 2:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .