Modules Flashcards
What is the module specification used by Node.js initially?
CommonJS
Why don’t browsers support CommonJS?
CommonJS loads modules synchronously.
When you use CommonJS, what bindings are available so it can interact with other modules? What do they do?
require
: a function that makes sure a module is loaded and returns its interface.
exports
: an object which is the interface object for the module. It starts out empty and you add properties to it to defined exported values.
Can require
only be used at the top-level, or can it be used in functions too?
Since require
is a normal function it can be used anywhere.
How do you declare your dependencies with CommonJS?
Call require
like this:
const ordinal = require("ordinal");
How do declare your interface in CommonJS?
Use exports
or module.exports
.
module.exports = { foo: "bar" };
What’s are two differences between a regular script and a ES module?
Regular scripts have bindings defined in the global scope and have no way to directly reference other scripts.
Modules get their own separate scope and support the import/export keywords to declare their dependencies and interface.
How to define an interface with ES modules?
The export
keyword can be put in front of a function, class, or binding definition.
export function doWork() { return 7; }
In ES Modules, how do you make the bindings from another module available in the current module?
The import
keyword
import { dayName } from "./dayname.js";
What is the default
keyword used for in ES Modules?
Often used for modules that export a single binding.
export default ["Winter", "Spring", "Summer", "Autumn"];
This binding can be imported without the braces around the variable name.
import seasonNames from "./seasonname.js";
How do you import all bindings from a module at the same time using ES Modules?
Use import *
. You provide a name, and that name will be bound to an object holding all the module’s exports.
import * as dayName from "./dayname.js"; console.log(dayName.dayName(3));