Why
allow code of different authors to work well together
Main goal
- Encapsulation
- Hiding private details from global scope
Methods
- DIY by using closure, object, class
- Node.js using require()
- ES6 using import and export
Using DIY Closure
usually by IIFE, so that everything is inside of that function scope
Using Node.js require()
To export
exports.foo = …
or to export a single item
modules.exports = …
To import
const http = require("http");
const stats = require("./stats.js");
webpack can use this format too… although, it might be better just to use the ES6 import and export
ES6 import export
- each file is a module
- all things private to the module unless explicitly exported
Export
all over the code, or at the end using one export keyword for things to export
export foo = 123;
export function bar() { … }
export class Wah…
Or, at the very end,
export { foo, bar, Wah };
Export Default
This is so that other modules can easily import it using
import Foo from "...";
and it was exported by
export default Foo;
Import
Import the default by
import Foo from "./Foo.js";
Import multiple exports by
import { foo, bar } from "./Foo.js"
Possible but a little uncommon to import both
import Foo, { bar, wah } from "./Foo.js"
Import renaming
import Foo as Bar from "./Foo.js"
It is possible to re-export too.
For more info, can refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
Top comments (0)