In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly shows you the "webpack4.x CommonJS modular example analysis", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "webpack4.x CommonJS modular example analysis" this article.
First, take a look at the description of the module in the official webpack documentation:
In modular programming, developers decompose the program into discrete function blocks (discrete chunks of functionality), which are called modules.
Each module has a smaller contact surface than the complete program, which makes it easy to verify, debug and test. Well-written modules provide reliable abstraction and encapsulation boundaries, so that each module in the application has a well-organized design and clear purpose.
One of the core concepts of webpack is that everything is modular. The role of webpack in a project is to analyze the structure of the project, find JavaScript modules and other extension languages (less,scss,typescript) that browsers cannot run directly, and package them into an appropriate format for browsers to use. It starts with the main file of a project and finds all the files it depends on according to the reference path. At the same time, these files are processed (parsed by various loader, compiled with files that cannot be directly used by browsers), and then packaged into one or more JavaScript files that browsers can recognize.
This article will not describe the construction process of webpack in detail. After all, the official website has already talked about it in more detail. Here, we mainly analyze the files packaged by webpack, what the files look like, and how to use the module. The earliest code modularization method supported by webpack is CommonJS, and then it gradually supports ES6, AMD, etc. No matter which method is used, webpack can parse and package it. In this example, CommonJS specification is used. For more specifications, please see the official documentation.
Examples
For the convenience of the following instructions, first create a project, that is, first create a folder webpack-test (name self-made), and then create a new package.json file in it to describe npm, and use the command in the webpack-test folder:
Npm init
Some questions will be asked after the execution of the command, and you can enter all the way. Then install the dependency package for webpack, as follows:
Npm install-save-dev webpack
Create a few more files:
1. Create a new folder app under the project root directory to store the business code, and the folder public to store the packaged files
2. Create a new entry file main.js in app
3. Create a new function module hello.js,bye.js,to.js in app
4. Create the index.html file under the root directory of the project
Then fill in the following contents for these documents in turn:
/ / webpack-test/app/hello.jsconst to = require ('. / to.js'); module.exports = function () {var hello = document.createElement ('div'); hello.textContent = "Say Hello to" + to.name; return hello;}; / / webpack-test/app/bye.jsconst to = require ('. / to.js'); module.exports = function () {var bye = document.createElement ('div'); bye.textContent = "Say Bye to" + to.name; return bye;} / / webpack-test/app/to.jsmodule.exports = {name: "Xiaoming"}; / / webpack-test/app/main.jsconst hello = require ('. / hello.js'); const bye = require ('. / bye.js'); document.querySelector ("# root") .appendChild (hello ()) .appendChild bye () / / webpack-test/index.html Webpack Test Project / / bundle.js file is the result file generated after we package the files in app in a moment.
The business modules hello.js and bye.js do their own operations, while referencing the common file to.js; master file main.js and executing the module hello.js and bye.js;index.html files. The final file bundle.js after main.js packaging is introduced.
Packing
Next, make sure that webpack is installed globally, otherwise you need to specify the path to webpack, such as using node_modules/.bin/webpack. / app/main.js. / public/bundle.js in version 4.0 or later.
If you are using webpack4.0+, using the webpack. / app/main.js. / public/bundle.js command may report the following error:
WARNING in configuration
The 'mode' option has not been set, webpack will fallback to' production' for this value. Set 'mode' option to' development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/concepts/mode/
ERROR in multi. / app/main.js. / public/bundle.js
Module not found: Error: Can't resolve'. / public/bundle.js' in'/ Users/zhaohaipeng/soyoung-project/webpack-test'
@ multi. / app/main.js. / public/bundle.js main [1]
After webpack4.0+, for the first error report, you need to specify the environment-mode development; the second error report, because we do not use the configuration file to package, but directly use the command to specify the packaging output location, so you need to declare the output file. To sum up, the correct command is as follows:
Webpack app/main.js-output public/bundle.js-mode development
Execution result:
➜webpack-test webpack app/main.js-output public/bundle.js-mode development
Hash: a4e2f9ecc51b64891624
Version: webpack 4.25.1
Time: 90ms
Built at: 2018-11-08 17:11:01
Asset Size Chunks Chunk Names
Bundle.js 5.16 KiB main [emitted] main
Entrypoint main = bundle.js
[. / app/bye.js] 165 bytes {main} [built]
[. / app/hello.js] 173 bytes {main} [built]
[. / app/main.js] 144 bytes {main} [built]
[. / app/to.js] 30 bytes {main} [built]
➜webpack-test
The browser opens the index.html file and you can see the result
Say Hello to Xiao Ming
Say Bye to Xiao Ming
However, as a tool that simplifies the difficulty of our development and makes it easy to use, webpack is obviously not convenient to package by typing a lot of commands as above, so let's use the configuration file to do it again:
Create the webpack.config.js file in the root directory, and configure the package entry and exit:
/ / webpack-test/webpack.config.jsmodule.exports = {mode: "development", / / webpack.0 need to declare the environment entry: _ _ dirname + "/ app/main.js", / / the only entry file output: {path: _ _ dirname + "/ public", / / the packaged file storage directory filename: "bundle.js" / / output file name}
When packaging again, you only need to use the command webpack, and webpack reads the webpack.config.js file under the current path by default.
Finally, the packaged bundle.js file removes the redundant comments and adjusts the code format, as follows:
/ / self-executing function with parameters composed of all modules. The situation is that key:value,key is the cache of the module name (function (modules) {/ / webpackBootstrap / / loaded module) to record the loading of the module, but also to avoid repeated packaging and save resources var installedModules = {} / / webpack uses the require method to load the module (simulate ConmmonJS reqiure ()). The function is to process the corresponding module according to the passed module id, add the loaded cache, execute, mark, and return exports function _ _ webpack_require__ (moduleId) {/ / moduleId is the module path / / check whether the module has been loaded. If loaded, return directly to the module if (installedModulus [moduleId]) {return installedModules [moduleId] .module } / / if the current module is not loaded, create it and store it in the cache var module = installedModules [moduleId] = {I: moduleId, l: false, exports: {}}; / / under the exports of the current module, that is, the module code is executed inside the module, highlighting the scope of modules.Call (module.exports, module, module.exports, _ _ webpack_require__) / / the tag module has loaded module.l = true; / / return the export content return module.exports;} / / mount attributes of the module, the module (_ _ webpack_modules__) _ _ webpack_require__.m = modules; / / mount attributes, and the module loads cache _ _ webpack_require__.c = installedModules / / not implemented in this code, do not analyze / / define the getter method _ _ webpack_require__.d = function (exports, name, getter) {/ / when the name property is not defined in the object itself, but inherited from the prototype chain Then define the getter method if (! _ webpack_require__.o (exports, name)) {Object.defineProperty (exports, name, {enumerable: true, get: getter}) in exports. }}; / / not implemented in this code, do not analyze / / define _ _ esModule in exports, define key as the attribute of Symbol (called in _ _ webpack_require__.t) / / define _ _ esModule on exports _ _ webpack_require__.r = function (exports) {if (typeof Symbol! = = 'undefined' & & Symbol.toStringTag) {Object.defineProperty (exports, Symbol.toStringTag, {value:' Module'}) } Object.defineProperty (exports,'_ esModule', {value: true});} / / not executed in this code Do not analyze / / create a pseudo-namespace object / / create a fake namespace object / / mode & 1: value is a module id, require it / / mode & 2: merge all properties of value into the ns / / mode & 4: return value when already ns object / / mode & 8 | 1: behave like require__ webpack_require__.t = function (value, mode) {if (mode & 1) value = _ _ webpack_require__ (value) If (mode & 8) return value; if ((mode & 4) & & typeof value = = 'object' & & value & & value.__esModule) return value; var ns = Object.create (null); _ _ webpack_require__.r (ns); Object.defineProperty (ns,' default', {enumerable: true, value: value}) If (mode & 2 & & typeof value! = 'string') for (var key in value) _ webpack_require__.d (ns, key, function (key) {return value [key];} .bind (null, key)); return ns;}; / / not implemented in this code, do not analyze / / getDefaultExport function for compatibility with non-harmony modules _ webpack_require__.n = function (module) {var getter = module & & module.__esModule? Function getDefault () {return module ['default'];}: function getModuleExports () {return module;}; _ _ webpack_require__.d (getter,' averse, getter); return getter;} / / Object.prototype.hasOwnProperty.call / / determine that an attribute is defined in the object itself and not inherited from the prototype chain _ _ webpack_require__.o = function (object, property) {return Object.prototype.hasOwnProperty.call (object, property);}; / _ _ webpack_public_path__ webpack_require__.p = "" / / load the entry module main.js and return exports, which starts execution from the entry file and recursively executes all dependencies and returns return _ _ webpack_require__ (_ _ webpack_require__.s = ". / app/main.js") }) ({". / app/bye.js": (function (module, exports, _ _ webpack_require__) {eval ("const to = _ _ webpack_require__ (/ *!. / to.js * /\". / app/to.js\ ");\ nmodule.exports = function () {\ n var bye = document.createElement ('div');\ n bye.textContent =\" Say Bye to\ "+ to.name;\ n return bye;\ n} \ n / app/hello.js: (function (module, exports) {eval ("module.exports = function () {\ n var hello = document.createElement ('div');\ nhello.textContent =\" Say Hello!\ ";\ n return hello;\ n};\ n\ ndocument.createElement # sourceURL=webpack:///./app/hello.js?") }), ". / app/main.js": (function (module, exports, _ _ webpack_require__) {eval ("const hello = _ _ webpack_require__ (/ *!. / hello.js * /\". / app/hello.js\ ");\ nconst bye = _ _ webpack_require__ (/ *. / bye.js * /\". / app/bye.js\ ") \ n\ ndocument.querySelector (\ "# root\") .appendChild (hello ()) .appendChild (bye ());\ n\ neval # sourceURL=webpack:///./app/main.js? ");}),". / app/to.js ": (function (module, exports) {eval (" module.exports = {name:\ "Xiaoming\"};\ n\ nUnip # sourceURL=webpack:///./app/to.js? ");})}))
Analysis.
The running process of webpack can be divided into: reading configuration parameters, instantiating plug-ins, module parsing processing (loader), and outputting packaging files; in the above example, only references to JavaScript are used, and plug-ins and modules such as CSS, less, images and other modules that need to be processed by loader are not used, so in the above example, the process is only to read the configuration, identify the portal and its reference module, package a few steps, and generate the final bundle.js file.
Briefly describe the execution flow of webpack in this process: read the entry in the configuration file, and if there is a configuration plugins parameter, then instantiate the plug-in and bind the hook function at this time. Module parsing, that is, the moment when loader is added, starting from the entry file, according to the dependence of the entry file on other modules, combined with the loader (loader) instructions used for different types of files in the configuration file, parsing these modules step by step, or compressing, or escaping, to generate content that can be directly recognized by the browser; finally, all modules are packaged and the packaged files are output. In the above code, the content of bundle.js has been commented, so let's analyze the execution process of bundle.js:
1. Self-executing function
The final output file bundle.js is a JavaScript file, which is actually a self-executing function.
(function (parameter) {}) (parameter).
2. Parameters
The parameters of the self-executing method are the objects composed of all modules, the key is the path of each module, and the value is the execution code within each module. By observing the code inside the parameters and comparing the source code before packaging, you can find that all require has become the webpack custom module call method of _ _ webpack_require__, and the relative path in the source code has also become the relative path of the file in the final execution location.
{". / app/bye.js": (function (module, exports, _ _ webpack_require__) {eval ("const to = _ _ webpack_require__ (/ *!. / to.js * /\". / app/to.js\ ");\ nmodule.exports = function () {\ n var bye = document.createElement ('div');\ n bye.textContent =\" Say Bye to\ "+ to.name;\ n return bye;\ n} \ n / app/hello.js: (function (module, exports) {eval ("module.exports = function () {\ n var hello = document.createElement ('div');\ nhello.textContent =\" Say Hello!\ ";\ n return hello;\ n};\ n\ ndocument.createElement # sourceURL=webpack:///./app/hello.js?") }), ". / app/main.js": (function (module, exports, _ _ webpack_require__) {eval ("const hello = _ _ webpack_require__ (/ *!. / hello.js * /\". / app/hello.js\ ");\ nconst bye = _ _ webpack_require__ (/ *. / bye.js * /\". / app/bye.js\ ") \ n\ ndocument.querySelector (\ "# root\") .appendChild (hello ()) .appendChild (bye ());\ n\ neval # sourceURL=webpack:///./app/main.js? ");}),". / app/to.js ": (function (module, exports) {eval (" module.exports = {name:\ "Xiaoming\"};\ n\ nUnip # sourceURL=webpack:///./app/to.js? ");})})}
3. Execution
(1) from the beginning of the execution file to the bottom of the self-execution function, load from the entry file first.
Return _ _ webpack_require__ (_ _ webpack_require__.s = ". / app/main.js")
(2) the _ _ webpack_require__ function is called, passing in the parameter. / app/main.js
Function _ webpack_require__ (moduleId) {/ / moduleId is. / app/main.js / / for the first time, and the module has not yet cached if (installedModules [moduleId]) {return installedModules [moduleId] .modules } / New. / app/main.js module, which is stored in cache var module = installedModules [moduleId] = {I: moduleId, l: false, exports: {}}; modules [moduleId] .call (module.exports, module, module.exports, _ _ webpack_require__); / / the tag module has loaded module.l = true; / / output module content return module.exports }
At this point, modules [moduleId] .call (module.exports, module, module.exports,__webpack_require__) is executed in the method; it is equivalent to executing the following code in a module named. / app/main.js:
(function (module, exports, _ _ webpack_require__) {eval ("const hello = _ _ webpack_require__ (/ *!. / hello.js * /\". / app/hello.js\ ");\ nconst bye = _ _ webpack_require__ (/ *. / bye.js * /\". / app/bye.js\ ");\ n\ ndocument.querySelector (\" # root\ ") .appendChild (hello ()) .appendChild (bye ()) \ n\ nCompact # sourceURL=webpack:///./app/main.js? ");}) ()
Because of the reference relationship, the _ _ webpack_require__ method is then executed twice again, passing the parameter module path. / app/hello.js and. / app/bye.js, respectively.
(3) execute the first _ _ webpack_require__ procedure, except for different parameters and different modules, which is basically the same as the second step. Find the dependent module to.js again, and call _ _ webpack_require__ again.
". / app/hello.js": (function (module, exports, _ _ webpack_require__) {eval ("const to = _ _ webpack_require__ (/ *!. / to.js * /\". / app/to.js\ ");\ nmodule.exports = function () {\ n var hello = document.createElement ('div');\ nhello.textContent =\" Say Hello to\ "+ to.name;\ n return hello;\ n} \ n\ nCompact # sourceURL=webpack:///./app/hello.js? ");})
(4) when the second _ _ webpack_require__ is executed, the dependency on to.js is found in the bye.js, so the _ _ webpack_require__ method will continue to be called, but the parameter will be passed to. / app/to.js, reaching the end.
". / app/bye.js": (function (module, exports, _ _ webpack_require__) {eval ("const to = _ _ webpack_require__ (/ *!. / to.js * /\". / app/to.js\ ");\ nmodule.exports = function () {\ n var bye = document.createElement ('div');\ nbye.textContent =\" Say Bye to\ "+ to.name;\ n return bye;\ n} \ n\ nCompact # sourceURL=webpack:///./app/bye.js? ");})
(5) by this time, the entire parsing of the dependent module from the beginning of the entry file has been completed, and all the js code has been referenced and put into the bundle.js.
The above is all the content of the article "sample Analysis of webpack4.x CommonJS Modularization". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 266
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.