JavaScript Modules – How to Create, Import, and Export a Module in JS

JavaScript Modules:

JavaScript modules are a way to organize and structure code. They allow developers to break their code into smaller, reusable pieces. You can think about them as smaller pieces of code that you can import and export between different parts of an application.

Define a Module:

Here is the basic way to define a module. Imagine 2 files names, main.js  and generate.js.

main.js:

let name = "Rajamohan";

generate.js

function generateUserCertificate(Name, date){

const myName = name

generateUserCertificate(Name, "05-03-2023")

}

To use the "name" variable inside the generate.js file, you need to export it from the main.js file and import it into the generate.js file.

Export

Modules with functions or variables can be stored in any external file.

There are two types of exports: Named Exports and Default Exports.

Default Exports

Here's how to perform a default export in a JavaScript file:

function getAllUser();

export default getAllUser;


Named Exports

Named exports allow you to share multiple modules from a file, unlike default exports which can only have one in a file.

You won't need to use the "default" syntax when using named exports. Named exports also need to be enclosed in curly brackets if you are exporting more than one module.

code:

const name = "Rajamohan";

export name;


Import Modules:

import getAllUser from "getuser.js";

That's all – you can then proceed to use getAllUser the  function anywhere in that file.

Happy coding!

Sign In or Register to comment.