-
Book Overview & Buying
-
Table Of Contents
Full-Stack React, TypeScript, and Node - Second Edition
By :
ES6 modules are the modern way to create shareable pieces of code in JavaScript. In this section, we'll review how to use modules to separate our application's code and make it more encapsulated and shareable.
There is an older style of creating modules called CommonJS. This module declaration method uses the require keyword to import members of other modules and the module.exports syntax is used to export a module's members. It is slowly being replaced by ES6 modules, but you will still see it being used and so should be aware.
An ES6 module is a file that may expose its members, allowing other files to use its data and functionality. Let's look at a simple module example. Create a file called module.mjs (notice the mjs extension) and enter this code:
export let currentUser = {
name: "jon",
age: 20,
};
export default function hello() {
console.log("hello world");
}
In this example, we show two methods of exposing...