Modules Flashcards
Why do modules help with private data?
Modules can also make it easier to work with private data, which helps maintain encapsulation. You must explicitly export the items you want to make available; everything else is private to the module
What are the two kinds of modules?
CommonJS and ES6
How do we import a commonJS module
Using require():
const { logIt, setPrefix } = require(“./logit”);
logIt(“You rock!”); //»_space; You rock!
setPrefix(“++ “);
logIt(“You rock!”); // ++ You rock!
//Note that we’re using object destructuring to extract
// the two functions from the object returned by require.
how do we do a commonJS export
let prefix = “» “;
function logIt(string) {
console.log(${prefix}${string}
);
}
function setPrefix(newPrefix) {
prefix = newPrefix;
}
module.exports = {
logIt,
setPrefix,
};
What is all node code part of
In Node, all code is part of a CommonJS module, including your main program. Each module provides several variables that you can use in your code:
-
Module
: an object that represents the current module -
exports
: the name(s) exported by the module (same asmodule.exports
) -
require(moduleName)
: the function that loads a module -
\_\_dirname
: the absolute pathname of the directory that contains the module -
\_\_filename
: the absolute pathname of the file that contains the module
How do we import ECMAScript modules
import { bar } from “./bar”;
let xyz = 1; // not exported
export function foo() {
console.log(xyz);
xyz += 1;
bar();
}
how do we change an ECMAScript imports name
import { foo as renamedFoo } from “./foo”;
renamedFoo(); // 1
how do we import all declarations from a file using ECMAScript
import * as FooModule from “./foo”;
FooModule.foo(); // 1
We can import all declarations from a file using the*syntax and then access them using the dot (.) syntax. This is called aNamespace import.
How do we define a default export?
function bar() {
console.log(2);
}
import bar from “./bar”;
bar(); // 2
How can we use ES modules in node?
Please note that Node.js, by default, does not directly support ES6 modules. However, newer versions of Node.js offer methods to use ES modules either by changing the file extension of the module file to.mjsor by making changes to thepackage.jsonfile.
//package.json
{
“name”: “index”,
“version”: “1.0.0”,
“description”: “”,
“main”: “index.js”,
“type”: “module”,
“scripts”: {
“test”: “echo "Error: no test specified" && exit 1”
},
“keywords”: [],
“author”: “”,
“license”: “ISC”
}