Loading Please Wait...

Logo Lynxsia IT Solutions

JavaScript Module

JS Module

JavaScript modules allow you to break up your code into separate files. This makes it easier to maintain a code-base.

Modules are imported from external files with the import statement. Modules also rely on type="module" in the <script> tag.

					 
        
          <script type="module">
            import countries from "./countries.js";
          </script>
        
      
Export

Modules with functions or variables can be stored in any external file. There are two types of exports: Named Exports and Default Exports.

Named Exports

Let us create a file named country.js, and fill it with the things we want to export.

You can create named exports two ways. In-line individually, or all at once at the bottom.

					 
        
          // inline individually
          export const name = "India";
          export const capital = "Delhi";

          // all at once
          const name = "India";
          const capital = "Delhi";
          export {name, capital};
        
      
Default Exports

Let us create a file named country.js, and use it for demonstrating default export.

You can only have one default export in a file.

					 
        
          const country = () => {
            const name = "India";
            const capital = "Delhi";
            return "Capital of " + name + " is " + capital;
          };

          export default country;
        
      
Import

You can import modules into a file in two ways, based on if they are named exports or default exports.

Named exports are constructed using curly braces. Default exports are not.

Name Import
					 
        
          import { name, capital } from "./country.js";
        
      
Default Import
					 
        
          import country from "./country.js";
        
      
Precaution

Modules only work with the HTTP(s) protocol.

A web-page opened via the file:// protocol cannot use import / export.

How you feel about this blog:

Share this blog on:

Report Us

If you find any error in the turtorials, or want to share your suggestion/feedback, feel free to send us email at: info@lynxsia.com

Contact Us
Ads
Logo
Lynxsia IT Solutions

We are concern with various development process like website design & development, E-commerce development, Software development, Application development, SMS & Bulk SMS Provider, PWA Development, and many more..

Kotwali Road, Chhiptehri, Banda, 210001, UP, India

Copyright © 2022, Lynxsia IT Solutions, All rights reserved