in

Introduction to JavaScript’s module system

javascript cover image

[ad_1]

The concept of modules comes from the modular programming paradigm. This paradigm proposes that software should be composed of discrete, interchangeable components called “modules” by dividing program functionality into stand-alone files that either operate independently or can be combined in an application. .

Modules are stand-alone files that encapsulate code to implement specific functionality and promote reusability and organization.

Here we discuss the module systems used in JavaScript applications, including the module pattern, the CommonJS module system used in most Node.js applications, and the ES6 module system.


module pattern

Before the introduction of native JavaScript modules, the module design pattern was used as a module system for scoping variables and functions to a single file.

This was implemented using an immediately-invoked function expression, commonly known as an IIFE. IIFEs are non-reusable functions that execute as soon as they are created.

The basic structure of IIFE is:

 (function () {
  
})();
  
(() => {
  
})();
  
(async () => {
  
})();

The code block above describes an IIFE used in three different contexts.

IIFE was used because variables declared within a function are scoped to the function, are only accessible within the function, and can return data by the function (making them publicly accessible). ) because

for example:

 const foo = (function () {
  const sayName = (name) => {
    console.log(`Hey, my name is ${name}`);
  };

  
  return {
    callSayName: (name) => sayName(name),
  };
})();
foo.callSayName("Bar");

The above code block is an example of how modules were written before native JavaScript modules were introduced.

The code block above contains an IIFE. The IIFE contains functions that make it accessible by returning it. All variables declared with IIFE are protected from global scope. So the method (say the name) can only be accessed via public functions. callSayName.

Notice that the IIFE is saved in a variable. PhewThis is because if the variable does not point to a location in memory, it will not be accessible after the script runs. This pattern can occur due to JavaScript closures.

CommonJS module system

The CommonJS module system is a module format defined by the CommonJS group to solve the JavaScript scoping problem by having each module run in its own namespace.

The CommonJS module system works by forcing modules to explicitly export the variables they expose to other modules.

This module system was created for server-side JavaScript (Node.js) and is not supported by default in browsers.

To implement CommonJS modules in your project, you must first initialize NPM in your application by running the following command:

 npm init -y

Variables exported according to the CommonJS module system can be imported as follows:

 


const installedImport = require("package-name");


const localImport = require("/path-to-module");

The module is imported into CommonJS. Required This statement reads a JavaScript file, executes the read file, and export object.of export object contains all exports available in the module.

You can export variables according to the CommonJS module system using named exports or default exports.

named export

A named export is an export identified by an assigned name. Named exports allow multiple exports per module, unlike default exports.

for example:

 

exports.myExport = function () {
  console.log("This is an example of a named export");
};

exports.anotherExport = function () {
  console.log("This is another example of a named export");
};

The code block above exports two named functions (my export and another export) by attaching them to export object.

Similarly, you can export a function like this:

 const myExport = function () {
  console.log("This is an example of a named export");
};

const anotherExport = function () {
  console.log("This is another example of a named export");
};

module.exports = {
  myExport,
  anotherExport,
};

In the code block above, export Opposes the specified function.can only be assigned export through an object to a new object module object.

The code will throw an error if you try to run it this way.

 
exports = {
  myExport,
  anotherExport,
};

There are two ways to import named exports:

1. Import all exports as one object and access them individually using dot notation.

for example:

 

const foo = require("./main");

foo.myExport();
foo.anotherExport();

2. Explode the export from export object.

for example:

 

const { myExport, anotherExport } = require("./main");

myExport();
anotherExport();

What all import methods have in common is that they must be imported using the same names they were exported with.

Default export

The default export is the export identified by any name. You can only have one default export per module.

for example:

 
class Foo {
  bar() {
    console.log("This is an example of a default export");
  }
}

module.exports = Foo;

In the code block above, we are exporting a class (Fu) by reassigning export object to it.

Importing default exports is similar to importing named exports, except that you can import using any name.

for example:

 
const Bar = require("./main");

const object = new Bar();

object.bar();

In the code block above, the default exports are named. barbut you can use any name.

ES6 module system

The ECMAScript Harmony module system, commonly known as ES6 modules, is the official JavaScript module system.

ES6 modules are supported by browsers and servers, but require a little configuration before they can be used.

In the browser you have to specify type As module In the script import tag.

It seems like:

 
<script src="./app.js" type="module"></script>

In Node.js you have to set type To module your package.json File.

It seems like:

 
"type":"module"

You can also export variables using the ES6 module system using named exports or default exports.

named export

Similar to named imports in CommonJS modules, multiple exports per module are possible, identified by an assigned name.

for example:

 
export const myExport = function () {
  console.log("This is an example of a named export");
};

export const anotherExport = function () {
  console.log("This is another example of a named export");
};

In the ES6 module system, before variables export keyword.

A named export can be imported into another module in ES6 in the same way as in CommonJS.

  • Destructuring required exports from export object.
  • Import all exports as a single object and access them individually using dot notation.

Below is an unstructured example.

 
import { myExport, anotherExport } from "./main.js";

myExport()
anotherExport()

Here’s an example that imports an entire object:

 import * as foo from './main.js'

foo.myExport()
foo.anotherExport()

In the code block above, an asterisk (*) means “all”.of As Keyword is export In this case, it opposes the string that follows it. Phew.

Default export

Similar to CommonJS default exports, you can only have one default export per module, identified by any name you choose.

for example:

 
class Foo {
  bar() {
    console.log("This is an example of a default export");
  }
}

export default Foo;

The default export is Default Keyword after export The keyword is followed by the name of the export.

Importing default exports is similar to importing named exports, except that you can import using any name.

for example:

 
import Bar from "./main.js";

mixed export

The ES6 module standard allows a module to have both default and named exports, unlike CommonJS.

for example:

 
export const myExport = function () {
  console.log("This is another example of a named export");
};

class Foo {
  bar() {
    console.log("This is an example of a default export");
  }
}

export default Foo;

Importance of modules

Dividing your code into modules not only makes your code easier to read, it also makes it more reusable and maintainable. Using modules in JavaScript also makes your code less error prone, as all modules run in strict mode by default.

[ad_2]

Source link

What do you think?

Leave a Reply

GIPHY App Key not set. Please check settings

    FRnWTX2nKVRbabrmymdbhm 1200 80

    Samsung Galaxy Z Flip 5: latest news, rumors and everything we know so far

    iStock 1283724446 1

    11 best free website builders