介绍
前端模块化开发通常会用到commonJS或ES6提供的模块化语法,此处介绍通过commonJS时,webpack打包生成文件的代码
webpack版本:3.6.0
打包前的文件
// main.js
const {
add, mul } = require('./mathUtils.js')
console.log(add(20, 50))
console.log(mul(20, 50))
// mathUtils.js
function add(a, b) {
return a + b;
}
function mul(a, b) {
return a * b;
}
module.exports = {
add,
mul
}
// index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="./dist/bundle.js"></script>
</body>
</html>
打包后
终端运行webpack ./src/main.js ./dist/bundle.js
进行打包
打包生成bundle.js,注意我们已经在index.html中引入了它,此时运行index.html,在控制台中可以看到运行结果
一切正常,接下来进入正题,开始解析源码
代码解析
完整代码
/******/ (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,
/******/