前言
算是一个h5开发了,虽然没写过什么完整的前端页面,但接触前端也有段时间了,对于一个合格的前端开发者而言,搞懂 webpack 打包原理还是比较重要的
hello world
使用 commonjs 规范,lib.js 只导出一个方法
1 2 3 4
| // lib.js module.exports = function () { return "hello webpack!" }
|
index.js 使用 require 引入,代码很简单,输入方法返回值
1 2 3 4 5 6
| // index.js const func = require("./lib")
const result = func() // print hello console.log(result)
|
目录结构
1 2 3 4 5 6 7 8 9 10
| . ├── dist │ └── main.js ├── package-lock.json ├── package.json ├── node_modules ├── src │ ├── index.js │ └── lib.js └── webpack.config.js
|
webpack.config.js
为了方便看生成的源码,我们将 mode 设置为 development,
1 2 3 4 5 6 7 8 9 10 11
| var path = require('path');
module.exports = { context: path.resolve(__dirname, './'), mode: 'development', entry: './src/index.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'main.js' } };
|
package.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| { "name": "webpack-demo", "version": "1.0.0", "description": "", "private": true, "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "webpack" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "webpack": "^4.35.2", "webpack-cli": "^3.3.5" }, "dependencies": {} }
|
编译运行
1 2
| npm run build node dist/main.js
|
输出
1 2
| $ node dist/main.js hello webpack!
|
起源
浏览器,node 并不支持模块化,我们在项目中使用的 require、export 将会经过 webpack 后,这些 js 就会被打包整合成一个 js 文件,只需要运行 js 文件,整个模块将会运行起来了。
main.js 解析
整个文件只有 111 行,这是未经过压缩的版本,生产环境下的输出文件比这还要精简,只需要在 webpack.config.js 中将 mode 值等于 production 即可改变打包环境
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
| /******/ (function(modules) { // webpackBootstrap /******/ // 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; /******/ } /******/ // 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; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // 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 }); /******/ }; /******/ /******/ // 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; /******/ }; /******/ /******/ // 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, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = "./src/index.js"); /******/ }) /************************************************************************/ /******/ ({
/***/ "./src/index.js": /*!**********************!*\ !*** ./src/index.js ***! \**********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) {
eval("// index.js\nconst func = __webpack_require__(/*! ./lib */ \"./src/lib.js\")\n\nconst result = func()\n// print hello\nconsole.log(result)\n\n//# sourceURL=webpack:///./src/index.js?");
/***/ }),
/***/ "./src/lib.js": /*!********************!*\ !*** ./src/lib.js ***! \********************/ /*! no static exports found */ /***/ (function(module, exports) {
eval("module.exports = function () {\n return \"hello webpack!\"\n}\n\n//# sourceURL=webpack:///./src/lib.js?");
/***/ })
/******/ });
|
我们先将此文件的主要部分拿出来看
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| /******/ (function (modules) { var installedModules = {}
function __webpack_require__ (moduleId) { if (installedModules[moduleId]) { return installedModules[moduleId].exports } var module = installedModules[moduleId] = { i: moduleId, l: false, exports: {}
} modules[moduleId].call(module.exports, module, module.exports, __webpack_require__) module.l = true return module.exports }
return __webpack_require__(__webpack_require__.s = './src/index.js') }) ({ './src/index.js': (function (module, exports, __webpack_require__) { eval( '// index.js\nconst func = __webpack_require__(/*! ./lib */ "./src/lib.js")\n\nconst result = func()\n// print hello\nconsole.log(result)\n\n//# sourceURL=webpack:///./src/index.js?') }), './src/lib.js': (function (module, exports) { eval( 'module.exports = function () {\n return "hello webpack!"\n}\n\n//# sourceURL=webpack:///./src/lib.js?') }) })
|
这是一个立即执行函数,首先申明了 installedModules 对象,这是已安装的模块集合,之后定义了一个函数 webpack_require ,此函数用来获取模块的引用,最后 return 了此函数,参数为入口,moduleId = ‘./src/index.js’
modules 即为
1 2 3 4 5 6 7 8 9 10 11 12
| { './src/index.js': (function (module, exports, __webpack_require__) { eval( '// index.js\nconst func = __webpack_require__(/*! ./lib */ "./src/lib.js")\n\nconst result = func()\n// print hello\nconsole.log(result)\n\n//# sourceURL=webpack:///./src/index.js?') }), './src/lib.js': (function (module, exports) { eval( 'module.exports = function () {\n return "hello webpack!"\n}\n\n//# sourceURL=webpack:///./src/lib.js?') }) }
|
1
| modules[moduleId].call(module.exports, module, module.exports, __webpack_require__)
|
module 即模块,modules[moduleId] 即为
1 2 3 4
| (function (module, exports, __webpack_require__) { eval( '// index.js\nconst func = __webpack_require__(/*! ./lib */ "./src/lib.js")\n\nconst result = func()\n// print hello\nconsole.log(result)\n\n//# sourceURL=webpack:///./src/index.js?') })
|
module.exports 为 this 上下文环境,该函数执行中,第一行即调用
1
| const func = __webpack_require__("./src/lib.js")
|
webpack_require("./src/lib.js") 即调用了此函数
1 2 3 4
| (function (module, exports) { eval( 'module.exports = function () {\n return "hello webpack!"\n}\n\n//# sourceURL=webpack:///./src/lib.js?') })
|
最后返回 module.exports 即 lib 里面的导出函数。再往后执行便是
1 2 3
| const result = func() // print hello console.log(result)
|
此刻基本已经将关系理顺了,此后如果在调用模块,则世界从 installedModules 中直接返回。
总结
此文只是分析了简单的模块引用,需要仔细分析才能融会贯通。