Last active
January 8, 2016 05:30
-
-
Save flarnie/69eeb636bc9d9a7a827d to your computer and use it in GitHub Desktop.
A simplified and annotated example of how JavaScript is loaded in the bundle by webpack.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* In this simplified example, | |
* '_application.js' is our entry point | |
* and it requires 'init.js', | |
* which in turn requires both the 'home_view' | |
* and the 'current_user_model' | |
*/ | |
var modules = [ | |
// dependencies can be referenced by index | |
function() { | |
//... contents of ‘_application.js’ | |
}, | |
function() { | |
//... contents of ‘init.js’ | |
}, | |
function() { | |
//... contents of ./views/home_view.js’ | |
}, | |
function() { | |
//... contents of ./models/current_user_model.js’ | |
}, | |
]; | |
// This function gets called right away | |
// with the modules above as a parameter. | |
(function(modules) { | |
// The module cache | |
var installedModules = {}; | |
// The require function | |
function __webpack_require__(moduleId) { | |
// Check if module is in cache | |
if(installedModules[moduleId]) | |
return installedModules[moduleId].exports; | |
// If the module isn't in the cache - | |
// Create a new module (and put it into the cache) | |
var module = installedModules[moduleId] = { | |
exports: {}, | |
id: moduleId, | |
loaded: false | |
}; | |
// Execute the module function | |
// Meaning the method at index 'moduleId' | |
// in the 'modules' array gets called | |
// with access to the 'module', 'module.exports', | |
// and using '__webpack_require__' | |
// wherever your script called 'require' | |
modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); | |
// Flag the module as loaded | |
module.loaded = true; | |
// Return the exports of the module | |
return module.exports; | |
}; | |
// ... | |
// Load entry module and return exports | |
// Meaning this will run '__webpack_require__' | |
// with index 0 of the modules array | |
return __webpack_require__(0); | |
})(modules); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment