¶A background on modules
JavaScript programs started off pretty small — most of its usage in the early days was to do isolated scripting tasks, providing a bit of interactivity to your web pages where needed, so large scripts were generally not needed. Fast forward a few years and we now have complete applications being run in browsers with a lot of JavaScript, as well as JavaScript being used in other contexts (Node.js, for example).
It has therefore made sense in recent years to start thinking about providing mechanisms for splitting JavaScript programs up into separate modules that can be imported when needed. Node.js has had this ability for a long time, and there are a number of JavaScript libraries and frameworks that enable module usage (for example, other CommonJS and AMD-based module systems like RequireJS, and more recently Webpack and Babel).
- At its core, webpack is a static module bundler for modern JavaScript applications. When webpack processes your application, it internally builds a dependency graph from one or more entry points and then combines every module your project needs into one or more bundles, which are static assets to serve your content from.
- Babel is a JavaScript compiler.
modern browsers have started to support module functionality natively
¶Introducing an example
To demonstrate usage of modules, we've created a simple set of examples that you can find on GitHub.
git clone https://github.com/mdn/js-examples.git
¶Basic example structure
In our first example (see basic-modules) we have a file structure as follows:
basic-modules/
├── index.html
├── main.js
└── modules
├── canvas.js
└── square.js
2 directories, 4 files
- ./modules/canvas.js as
function create(id, parent, width, height) {
let divWrapper = document.createElement('div');
let canvasElem = document.createElement('canvas');
parent.appendChild(divWrapper);
divWrapper.appendChild(canvasElem);
divWrapper.id = id;
canvasElem.width = width;
canvasElem.height = height;
let ctx = canvasElem.getContext('2d');
return {
ctx: ctx,
id: id
};
}
function createReportList(wrapperId) {
let list = document.createElement('ul');
list.id = wrapperId + '-reporter';
let canvasWrapper = document.getElementById(wrapperId);
canvasWrapper.appendChild(list);
return list.id;
}
export { create, createReportList };