This article mainly introduces how Webpack loads modules. The content is quite good. I will share it with you now and give it as a reference.
Webpack is very popular among developers as a module packaging tool in front-end development. Its rich loaders enable it to implement a variety of functions. This article will use webpack to package a js file and see how webpack loads each module.
Two simple source files
In order to facilitate the analysis of the principle of webpack loading modules, we have prepared two files:
hello.js
const hello = { say: arg => { console.info('hello ' + arg || 'world'); } }; export default hello;
index.js
import Hello from './hello'; Hello.say('man');
index .js serves as the entry file and references the hello.js module.
Webpack packaging
Execute webpack index.js bundle.js on the command line to package the entry file and generate bundle.js , the general structure is (for the convenience of reading, I deleted some redundant code):
As you can see, the final generated file ends with (function (modules) {})([Module 1, Module 2]). The modules we define are packaged into anonymous functions, and then passed to an anonymous function function (modules) {} in the form of an array. In this anonymous function A __webpack_require__() function is defined to load the module. Finally, the first module index.js is loaded by return __webpack_require__(__webpack_require__.s = 0);
##__webpack_require__( ) Function
function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if (installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ }
Parameters accepted by the module
(function (module, __webpack_exports__, __webpack_require__) { "use strict"; const hello = { say: arg => { console.info('hello ' + arg || 'world'); } }; /* harmony default export */ __webpack_exports__["a"] = (hello); /***/ })
module, __webpack_exports__, __webpack_require__ to the module. The first two parameters are used to export variables in the module, and the third parameter is the one introduced earlier.
__webpack_require__() reference, used to import other modules.
Methods for react project framework based on webpack4
Three ways to create components in React and their differences
The above is the detailed content of How to use Webpack to load modules. For more information, please follow other related articles on the PHP Chinese website!