// -- rectangle.cjs --
module.exports = {
area: (a, b) => a * b,
};Modules across platforms / notebook
Modules across platforms
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
// -- square.cjs --
const rectangle = require("./rectangle.cjs");
// `rectangle` contains the `module.exports` object of rectangle.cjs
module.exports = {
area: (side) => rectangle.area(side, side),
};// -- rectangle.js --
define([], function () {
return {
area: (a, b) => a * b,
};
});// -- square.js --
define(["./rectangle"], function (rectangle) {
// `rectangle` contains the value returned by rectangle.js's factory
return {
area: (side) => rectangle.area(side, side),
};
});// -- rectangle.js --
(function (root, factory) {
if (typeof define === "function" && define.amd) {
define([], factory);
} else if (typeof module === "object" && module.exports) {
module.exports = factory();
} else {
root.rectangle = factory();
}
})(globalThis, function () {
return {
area: (a, b) => a * b,
};
});// -- square.js --
(function (root, factory) {
if (typeof define === "function" && define.amd) {
define(["./rectangle"], factory);
} else if (typeof module === "object" && module.exports) {
module.exports = factory(require("./rectangle.js"));
} else {
root.square = factory(root.rectangle);
}
})(globalThis, function (rectangle) {
return {
area: (side) => rectangle.area(side, side),
};
});// -- square.js --
export const area = (side) => side ** 2;// -- main.js --
import { area } from "./square.js";
console.log(area(4)); // 16import { readFile } from "node:fs/promises"; // Import from built-in module
import _ from "lodash"; // Import from package in node_modules
const text = await readFile(new URL("./data.txt", import.meta.url), "utf8");
const wordCounts = _.countBy(_.words(text));// -- main.mjs --
import square from "./square.cjs";
console.log(square.area(4)); // 16const square = require("./square.mjs");
// Assuming square.mjs and its dependencies do not use top-level await
console.log(square.area(4));
import("./module-with-top-level-await.mjs").then((mod) => {
mod.foo();
});