The braces are just syntactic sugar. It will use the variable name as the object key, for example:
const a = 1;
const test = {a}; // same as {a: 1};
It can also be used to destructure the object by its variable name. It will check if the object has any properties with the same value as the variable name and then output a value if one is found:
const test = {a: 1};
const {a} = test; // a = 1
In modules, the general use case is that when you import there is usually braces since modules get imported as MODULE.function
or MODULE.class
. It'd be more intuitive to look at exports first:
For exporting, it's using the syntactic sugar I mentioned before - you're exporting it as an object. When you do export { WebApi };
what you're really doing is export {WebApi: WebApi}
. This makes it easier to access things as you can just do 'MODULE.WebApi' now to access the class instead of having it pollute the namespace unnecessarily. This is also required for all exports!
Moving on to imports, what you're doing in the import statements is essentially destructuring the module object and picking a property to save into a variable of the same name. In your case, when you do import {WebApi} from './src/web-api.js'
you'd be doing something like import WebApi = web-api.js['WebApi'] from './src/web-api.js'
(this isn't valid syntax but just to show you what it's doing in the background). This is also required to properly import module functions/classes. There is also the option of importing the whole module, just as NodeJS does: import * as ModuleName from './src/module.js'
. This will put all of exported functions/classes into the ModuleName object so that it can be treated as a normal module.
However, if a module has a default
export, braces are not not needed for import and export. For example, react probably has export default React
in its files - that's why there doesn't need to be braces around it when you do import React from 'react'
Hope I wasn't too confusing and let me know if I can clarify anything!