I came to realize the concepts of CMD and AMD while playing with NodeJS, but it didn’t seem very useful for me back then since all the tiny demos I was working on are quite small ones, so module loader never occurs to me as one of the necessities. But the project I am currently involved is much bigger than those little demos, and I was just following the existing module loader patterns with RequireJS. Here I would like to take some notes of RequireJS.
For starters, the API and samples on the official site are really good, I am just trying to add more my take here.
Basic
Introduct RequireJS to the project
In your entry html, add a script in a page with src set to be require.js, and add another attribute data-main, which represents the entry point for js modules.
RequireJS loads each dependency as a script tag. Make sure those dependencies are loaded in the right order. You’ll need to config in advance to make it work, for example:
Optimization
Since requireJS encourages to write one module per file, sooner or later you’ll end up creating many files, that’s why it is quite useful to optimize all those files for production.
RequireJS comes with r.js, the installation and usage is quite simple as listed in the api, here is what I did in configuration file: