Table of contents
Organizing JavaScript code into reusable modules allows for:
namespace cleanliness: variable names do not get reused and cause confusion
instead of calling doStuff, you would call moduleX.doStuff
you would ensure that moduleX is unique to the program
functional focus: have one piece of code do one thing and one thing well!
this also makes the code more portable and shareable
we don't even have to know how they work internally
- we just care that they do what we want them to do
Newer way of doing modules (used in React)
// moduletoExport.js
const moduleToExport = {
property1: "hi",
property2: function() { return true },
property3: function() { return "hi" }
}
// attention to this
export default moduleToExport
// moduleThatImports.js
import ImportedModule from ('./moduleToExport.js')
console.log(ImportedModule.property3)
Older way of doing modules
We might see an older way of doing modules in older code using the module
keyword:
// moduleToExport.js
const moduleToExport = {
property1: "hi",
property2: function() { return true },
property3: function() { return "hi" }
}
// attention to this
module.exports = moduleToExport
// moduleThatImports.js
const ImportedModule = require('./moduleToExport.js')
console.log(ImportedModule.property3)