JAVASCRIPT MODULES IN ES6

ES6 modules are stored in files such as lib.jsJS

DEFINITION

Definizione
Interfaccia pubblica
Obbiettivi dei moduli

ES6 MODULE OBJECTIVES

When we talk about hiding implementation details let us remember the example of the DVD player. The goals of the modules are:

  • Abstract the code, then create an API that allows us to work abstractly
  • Encapsulation, or enclosing the code in a capsule
  • Having created the public API, it is possible to reuse the code inside our application and in other applications

FIRST EXAMPLE AND ERROR CORS

To work with the modules we need to use the http protocol, if we have the folder we are testing index.html on on the desktop and we double-click it we get an error of CORS browser policy. The CORS policy prevents communication between different origins, so we must use a web server. The end of the post explains how to install XAMPP on windows. On the other hand, for those who use Visual Studio Code as their editor, it will be enough to install the extension Live Server and run HTML pages with this local web server.

Copy to Clipboard
Copy to Clipboard
Copy to Clipboard

MULTIPLE EXPORTS AND IMPORTS

In addition to functions, we can export classes, objects and primitive types as seen in the code example above.

EXPORT DEFAULT

A module can make a single export marked as default. However, we can use lakeyword export to export other objects.

Copy to Clipboard
Copy to Clipboard

INSTALL XAMPP ON WINDOWS

In computer science, a web server (or web server) is a software application that, running on a server, can handle web page transfer requests from a client, typically a web browser. Communication between server and client is via the HTTP protocol, which uses TCP port 80 (or 8080), or possibly the secure version HTTPS, which uses 443 instead. Web sites therefore reside on a web server by hosting. The collection of all interconnected web servers worldwide gives birth to the World Wide Web. (wikipedia)

XAMPP package: available for windows, Linux and Mac

Windows users

The easiest solution to install a web server is to install the XAMPP package

STEP 1: Download and install XAMPP

To download XAMPP click on the following link: https://www.apachefriends.org/it/download.html and select for download XAMPP for windows.

STEP 2: Run the installer following the steps and paying attention to the XAMPP installation folder (by default it should be C:\xampp).

STEP 3: Run XAMPP

Start -> XAMPP -> XAMPP Control Panel

STEP 4: Start the Apache Module

xampp

DEEPENING AI

Modules in JavaScript are a concept introduced to facilitate the organization and reusability of code, especially in large applications. With the introduction of the ECMAScript module (ES6) in 2015, JavaScript natively supported the import and export of functionality between separate files. Prior to ES6, one had to rely on solutions such as CommonJS or AMD (Asynchronous Module Definition).

What are modules in JavaScript?

Modules in JavaScript are self-contained blocks of code that contain variables, functions, classes, and other constructs. They allow code to be isolated and reused more efficiently. With modules, you can:

-Include only what is necessary: each module can export only those elements that need to be accessed from other files, hiding everything else.

-Avoid name collisions: thanks to separate namespaces, modules prevent global variables or functions from overlapping each other.

-Have cleaner, more maintainable code: they facilitate separation of responsibilities within an application.

Basic JavaScript module syntax (ES6).

1. Export (export).

To make parts of a module available to other files, the export statement is used. There are two main ways to export elements from a module: named export and default export.

-Named export: You export specific functions, objects, variables or classes from a module.

// modulo.js
export const pi = 3.14159;

export function somma(a, b) {
       return a + b;
}

export class Persona {
    constructor(nome) {
        this.nome = nome;
    }
}

-Default export: A module can have a default export. This is useful when you want to export a single main feature from a file.

// modulo.js
export default function saluto() {
console.log(“Ciao!“);
}

2. Import (import)

To use code from another module, you use the import statement. Again, you can do named imports or default imports.

-Named import: You import specific elements using curly brackets.

// main.js
import { pi, somma } from./modulo.js‘;

console.log(pi); // 3.14159
console.log(somma(2, 3)); // 5

-Import default: You can import the default value without the need for curly brackets.

// main.js
import saluto from./modulo.js‘;

saluto(); // Ciao!

You can combine named and default imports:

import saluto, { pi, somma } from./modulo.js‘;

3. Aliases in imports and exports

To avoid name conflicts, you can use aliases with the as operator:

-Alias in the import:

import { somma as addizione } from ‘./modulo.js‘;

console.log(addizione(2, 3)); // 5

-Alias in the export:

export { pi as piGreco };

4. Dynamic import

With dynamic import, you can load a module only when needed, delaying the import until runtime. You use the import() function:

// main.js
import(‘./modulo.js‘)
.then((modulo) => {

         console.log(modulo.somma(2, 3));
})
.catch((error) => {

        console.error(‘Errore nell’importazione‘, error);
});

Dynamic import is useful in contexts such as code splitting, where you load only the modules you need to optimize performance.

Benefits of JavaScript Modules

1. Better Code Organization: Instead of having all your code in one file, you can modularize your code into separate blocks.

2. Maintainability and Scalability: Modules make it easier to work on large projects or development teams, as each team can manage a specific module.

3. Code Reuse: You can export code from a module and reuse it in multiple other modules or applications.

4. Improved Performance: With the ability to dynamically load modules, you can reduce the initial load time of your web pages.

Types of Modules

1. ES6 Modules (Native): This is the standard module system for JavaScript. It works with the import/export statement and is natively supported by modern browsers and Node.js starting with the latest versions.

2. CommonJS: Primarily used in Node.js, CommonJS modules use module.exports and require to import and export modules. For example:

// modulo.js
module.exports = {
     saluto: function() {
        console.log(“Ciao!“);
     }
};

// main.js
const modulo = require(‘./modulo.js‘);
modulo.saluto();

Support and Compatibility

ES6 modules are supported by most modern browsers and Node.js. However, it is important to note that not all older browsers support modules out of the box. In these cases, you can use transpiling tools like Babel to convert your code into a form compatible with older environments.

Additionally, many modern applications use bundlers like Webpack or Rollup to manage and optimize the use of modules, making integration with different types of modules (ES6, CommonJS, etc.) easier and more compatible.

Example of using modules in a web project

In the context of a modern web application, JavaScript modules can be used like this:

1. HTML file:

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Moduli in JavaScript</title>
</head>
<body>
<script type=”module” src=”main.js“></script>
</body>
</html>

2. JavaScript file (module.js):

// modulo.js
export function saluto() {
console.log(‘Ciao dal modulo!‘);
}

3. Main JavaScript file (main.js):

import { saluto } from./modulo.js‘;

saluto(); // Output: Ciao dal modulo!

Conclusion

JavaScript modules have become an essential part of modern development, allowing for better code structure and significant improvements in maintainability, performance, and code reuse.

LINKS TO PREVIOUS POSTS

THE JAVASCRIPT LANGUAGE

LINK TO CODE ON GITHUB

GITHUB