JavaScript

Last Updated: 2/2/2023

Modules

  • You should not put all your JavaScript code in a single file because that's really hard to maintain
  • You should split your code into multiple files, and each file is called a module.

Benefits

  • Increase the maintainability of your application because the code is better organized.
  • You can reuse one or more modules in different parts of an application or in different applications.
  • You can abstract code by applying abstraction principle, which means you hide some of the complexity in a module, and only expose the essentials.

Before ES6

  • In ES5 you didn't have the concept of modules. So different solutions emerged to solve this problem.
  • The popular module formats are
    • AMD: asynchronous module definition, and is primarily used in browser applications.
    • CommonJS: used in Nodejs,
    • UMD: stands for universal module definition and can be used both in the browser and in Nodejs.

ES6 Modules

  • ES6 native supports module.
  • Each js file is a module
  • By default all members are private
  • Use export keyword to export one or more objects and import keyword to import objects from other modules.

Export

Named Export

message.js

export  const  messageSave = "Record is successfully saved";

Default Export

const messageWelcome = "Welcome to your website";
export default messageWelcome;

Mulitple Exports

export {
	messageSave, 
	messageWelcome
}

Import

  • ./ refers to the current folder of the file in which it is added

Named Import

index.js

import  {messageSave } from  "./message.js";

Default Import

import  messageWelcome  from  "./message.js";

Multiple Import

import { messageSave, messageWelcome } from  "./message.js";