Organize Code
Source File
JavaScript
// logger.js file
export function err(msg){ console.log("ERR: " + msg) }
export function warn(msg){ console.log("WARN: " + msg) }
export function info(msg){ console.log("INFO: " + msg) }
export default function(msg, type) {
switch (type) {
case 0:
err(msg)
break
case 1:
warn(msg)
break;
default:
info(msg);
}
}
Modules are introduced in JavaScript ES6.
There are community efforts to define modules before ES6:
Each module in JavaScript is defined in a separate file.
There are 2 ways to expose variables and objects in ES6 Modules:
- Default Export
- Named Export
You can use both of the export types in a same module at a same time.
// circle.js file
var PI = 3.14;
export default PI;
Default Exports are used to export and expose only one thing.
In Default Exports, only the reference to the entity being exported is being exposed, meaning that, in this circle.js module, the name PI is not visible to the developers using your module.
Other ways to rewrite this are:
export default var PI = 3.14;
export default 3.14;
// check 'circle.js' and 'logger.js' from previous cards.
import p from './circle.js';
import log from './logger.js';
log(p) // INFO: 3.14
For importing a default exported modules, you only need to specify the module path.
You are free to name p
here whatever you want.
Mentioning .js extensions are optional.
// square.js file
function area(w) { return w * w }
function circumference(w) { return 4 * w }
export {
area,
circumference as perimeter
}
Name Exports are used to export and expose multiple variables and objects.
In this square.js module we are exporting two functions:
area
function with the same namecircumference
function with a nameperimeter
Other way to rewrite this is to have the exports inline:
export function area(w) { return w * w }
export function perimeter(w) { return 4 * w }
// check 'square.js' and 'logger.js' from previous cards.
import { area as tiles, perimeter } from './square.js';
import { info } from './logger.js';
info(perimeter(2)) // INFO: 8
For importing Named Exports from a module you need to specify the name of objects or variables that are exported from that module with the path to the module.
You can rename the exported entities using keyword as
in your import.
// check 'square.js' and 'logger.js' from previous cards.
import * as sq from './square.js';
import * as logger from './logger.js';
logger.info(sq.area(2)); // INFO: 4
You can import all the Named Exports at once using *
.
All the imported names will be namespaced under the name you specify after as
.