2Minutes: JavaScript Modules (ES6 Standard)
Modules in JavaScript
In ES6 (ECMAScript 2015), JavaScript introduced modules. As we discussed in Lexical Scopes, variables and functions alike are only accessible within the context in which they are created. If we create a global variable or function in one file, we still can’t access it directly from another file.
// config.js
const API_URL = 'https://mouhammad.online/api';API_URL is only accessible within config.js, and that’s a problem. We need a way to access this variable elsewhere. For instance, we might need it in functions.js to fetch data from our API.
The Solution
ES6 introduced a clean standard to export data from one file and import it wherever we need it. We have the export and export default keywords. Both are used to make a file’s data available externally.
// config.js
export const API_URL = 'https://mouhammad.online/api';
// Or
export default API_URL;// functions.js
import { API_URL } from 'config.js';
// Now API_URL is accessible within functions.jsexport default serves the same purpose, but it represents the file’s primary export. Here’s how it’s used:
import API_URL from 'config.js'; // Notice that imported API_URL not { API_URL }Before ES6, we used to have the CommonJS module specification. It’s quite old now, and almost no one uses it for modern applications. However, it might be a topic for another post.
That’s 2Minutes Concept, see you in the next one.
Sources
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules
https://www.freecodecamp.org/news/javascript-modules-a-beginner-s-guide-783f7d7a5fcc