Which file extension does Node.js require for ECMAScript module files?
.mjs
Define two classes in a module, and export them (so they can be used in other modules).
export class ExportMe1 {
greet() { console.log("Hello 1"); }
}
export class ExportMe2 {
greet() { console.log("Hello 2"); }
}
// alternative to using the "export" keyword above:
// export { ExportMe1, ExportMe2 };
Explicitly import & use the two classes that were exported above.
import { ExportMe1, ExportMe2 } from "./exports.mjs";
new ExportMe1().greet();
new ExportMe2().greet();
Explicitly import & use the two classes that were exported above, but with import aliases.
import { ExportMe1 as Ex1, ExportMe2 as Ex2} from "./exports.mjs";
new Ex1().greet();
new Ex2().greet();
Implicitly import & use the two classes that were exported above.
import * as Imported from "./exports.mjs";
new Imported.ExportMe1().greet();
new Imported.ExportMe2().greet();
Define a class in a module as default export (so it can be used in other modules).
// there can be only one default export per module
export default class ExportMe3 {
greet() { console.log("Hello 3"); }
}
Explicitly import & use the class that was default-exported above.
// importing default exports doesn't need curly braces,
// and can be aliased on-the-fly without "as" syntax:
import Ex3 from "./exports-default.mjs";
new Ex3().greet();