Why are modules needed?
1) Isolation
2) File system organization
3) Reuse
Modules history
1) IIFE
(const a = 2; APP.number = a)()
Only works in the browser
2) require
module.exports = {a, b}
const {a,b} = require(some.js)
Only works in Node, and in the browser it is used only for assembly. Webpack actually also assembles everything on Node
3) ES modules
export
import
Differences between CommonJS and ES modules
CommonJS Modules:
1) Require anywhere
2) Can be used in conditions
3) Loads the entire module, even if we import a small part
4) Synchronous module loading, can block the thread
ES Modules:
1) Imports must always be at the top level
2) Cannot be used in conditions (except asynchronous)
3) Selectively loads parts of their module
4) Asynchronous module loading
How to use ES modules in Node?
1) Work with .mjs files
2) In package.json write type: “module”
3) Pass node argument –input-type=module
How is modules wrapped in Node?
All files wrapped with anonimous function -
function (exports, require, module, __filename, __dirname) {}