javascriptecmascript-6javascript-import

When do we use '{ }' in javascript imports?


I am learning Javascript imports and I am yet to understand when we use curly braces while importing items(functions, objects, variables) from another JS file.

import Search from './models/Search';
import * as searchView from './views/searchView';
import { elements, renderLoader } from './views/base'
//elements is an object, renderLoader is a function

Solution

  • import { elements, renderLoader } from './views/base'
    

    is the way you need to import single, named exports from a module, in this case it is importing named exports elements and renderLoader from base.js.

    The { elements, renderLoader } syntax is in many cases just syntactic sugar (called destructuring) added in recent versions of the ECMAScript standard.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring

    In this case, though, it is necessary to get only the named exports you want.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Import_a_single_export_from_a_module

    Please note that you can also pick new names for your variables like this:

    import { elements as newNameForElements, renderLoader as newNameForRenderLoader } from './views/base'
    

    which would then make the elements export available as newNameForElements etc.