Es6-Javascript Named and Default Modules Guide with examples

Es6-Javascript Named and Default Modules Guide with examples

    In this blog post, we’ll learn named and default modules in JavaScript or ES6, accompanied by examples.

    ES6 Modules

    JavaScript lacked support for modules in prior versions to ES6.

    ES6 introduced modules to facilitate code organization and reusability across different parts of applications.

    ES6 modules comprise JavaScript code containing variables and functions declared within the JavaScript file. However, these remain inaccessible unless explicitly exported. This feature, widely used by Node.js and client-side frameworks, offers a straightforward yet potent means of code organization.

    Advantages of Modules:

    • Code separation into multiple files enhances reusability.
    • All variables or functions defined within a module remain private to that module.
    • Modules can be reused in multiple other applications or modules
    • Modules are like packages in java which we can avoid namespace issues

    ECMAScript 2015 defines two types of modules:

    • Default Module: Modules containing a solitary entity per module.
    • Named Modules: Modules housing multiple entities within a single file.

    Import and Export Default Modules

    This single module is declared for export functionality. Modules need to be declared with an export keyword to make use of it in another part of the code. Import keyword is used to import the modules Here is a syntax for import and export Default module declaration.

    export default ModuleName // Export is declared with the export keyword
    

    Once exported, the module becomes accessible for use in other modules through the import keyword. Here’s the syntax for the import keyword:

    import ModuleName from 'filepath without extension'.