作者:王聪
进修目的
本质上,webpack 是一个当代 JavaScript 应用程序的静态模块打包器(module bundler)。当 webpack 处置惩罚应用程序时,它会递归地构建一个依靠关联图(dependency graph),个中包括应用程序须要的每一个模块,然后将所有这些模块打包成一个或多个 bundle。
经由历程minipack这个项目的源码进修相识上边提到的全部事情流程
demo目次
.
├── example
├── entry.js
├── message.js
├── name.js
进口文件 entry.js:
// 进口文件 entry.js
import message from './message.js';
console.log(message);
message.js
// message.js
import {name} from './name.js';
export default `hello ${name}!`;
name.js
// name.js
export const name = 'world';
进口文件
进口出发点(entry point)指导 webpack 应当运用哪一个模块,来作为构建其内部依靠图的最先。进入进口出发点后,webpack 会找出有哪些模块和库是进口出发点(直接和间接)依靠的。
createAsset:临盆一个形貌该模块的对象
createAsset 函数会剖析js文本,临盆一个形貌该模块的对象
function createAsset(filename) {
/*读取文件*/
const content = fs.readFileSync(filename, 'utf-8');
/*临盆ast*/
const ast = babylon.parse(content, {
sourceType: 'module',
});
/* 该数组将保留此模块所依靠的模块的相对途径。*/
const dependencies = [];
/*遍历AST以尝试明白该模块所依靠的模块。 为此,我们搜检AST中的每一个导入声明。*/
traverse(ast, {
ImportDeclaration: ({node}) => {
/*将导入的值推送到依靠项数组中。*/
dependencies.push(node.source.value);
},
});
const id = ID++;
/* 运用`babel-preset-env`将我们的代码转换为大多数浏览器能够运转的代码。*/
const {code} = transformFromAst(ast, null, {
presets: ['env'],
});
/*返回这个形貌对象*/
return {
id,
filename,
dependencies,
code,
};
}
createGraph: 临盆依靠关联图
function createGraph(entry) {
// 剖析进口文件
const mainAsset = createAsset(entry);
/*将运用行列来剖析每一个模块的依靠关联。 为此,定义了一个只包括进口模块的数组。*/
const queue = [mainAsset];
/*我们运用`for ... of`轮回迭代行列。 最初,行列只要一个模块,但在我们迭代它时,我们会将其他新模块推入行列。 当行列为空时,此轮回将停止。*/
for (const asset of queue) {
/*我们的每一个模块都有一个它所依靠的模块的相对途径列表。 我们将迭代它们,运用我们的`createAsset()`函数剖析它们,并跟踪该模块在此对象中的依靠关联。*/
asset.mapping = {};
// This is the directory this module is in.
const dirname = path.dirname(asset.filename);
// We iterate over the list of relative paths to its dependencies.
asset.dependencies.forEach(relativePath => {
// Our `createAsset()` function expects an absolute filename. The
// dependencies array is an array of relative paths. These paths are
// relative to the file that imported them. We can turn the relative path
// into an absolute one by joining it with the path to the directory of
// the parent asset.
const absolutePath = path.join(dirname, relativePath);
// Parse the asset, read its content, and extract its dependencies.
const child = createAsset(absolutePath);
// It's essential for us to know that `asset` depends on `child`. We
// express that relationship by adding a new property to the `mapping`
// object with the id of the child.
asset.mapping[relativePath] = child.id;
// Finally, we push the child asset into the queue so its dependencies
// will also be iterated over and parsed.
queue.push(child);
});
}
// At this point the queue is just an array with every module in the target
// application: This is how we represent our graph.
return queue;
}
经由历程createGraph函数 天生的依靠关联对象:
[
{ id: 0,
filename: './example/entry.js',
dependencies: [ './message.js' ],
code: '"use strict";\n\nvar _message = require("./message.js");\n\nvar _message2 = _interopRequireDefault(_message);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nconsole.log(_message2.default);',
mapping: { './message.js': 1 } },
{ id: 1,
filename: 'example/message.js',
dependencies: [ './name.js' ],
code: '"use strict";\n\nObject.defineProperty(exports, "__esModule", {\n value: true\n});\n\nvar _name = require("./name.js");\n\nexports.default = "hello " + _name.name + "!";',
mapping: { './name.js': 2 } },
{ id: 2,
filename: 'example/name.js',
dependencies: [],
code: '"use strict";\n\nObject.defineProperty(exports, "__esModule", {\n value: true\n});\nvar name = exports.name = \'world\';',
mapping: {} }
]
bundle 打包
bundle函数把上边获得的依靠关联对象作为参数,临盆浏览器能够运转的包
function bundle(graph) {
let modules = '';
graph.forEach(mod => {
modules += `${mod.id}: [
function (require, module, exports) {
${mod.code}
},
${JSON.stringify(mod.mapping)},
],`;
});
const result = `
(function(modules) {
function require(id) {
const [fn, mapping] = modules[id];
function localRequire(name) {
return require(mapping[name]);
}
const module = { exports : {} };
fn(localRequire, module, module.exports);
return module.exports;
}
require(0);
})({${modules}})
`;
// We simply return the result, hurray! :)
return result;
}
参考例子,终究临盆的代码:
(function (modules) {
function require(id) {
const [fn, mapping] = modules[id];
function localRequire(name) {
return require(mapping[name]);
}
const module = { exports: {} };
fn(localRequire, module, module.exports);
return module.exports;
}
require(0);
})({
0: [
function (require, module, exports) {
"use strict";
var _message = require("./message.js");
var _message2 = _interopRequireDefault(_message);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
console.log(_message2.default);
},
{ "./message.js": 1 },
],
1: [
function (require, module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _name = require("./name.js");
exports.default = "hello " + _name.name + "!";
},
{ "./name.js": 2 },
],
2: [
function (require, module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var name = exports.name = 'world';
},
{},
],
})
剖析打包后的这段代码
这是一个自实行函数
(function (modules) {
...
})({...})
函数体内声清楚明了 require
函数,并实行挪用了require(0);
require函数就是 从参数modules对象中找到对应id的 [fn, mapping]
假如模块有依靠其他模块的话,就会实行传入的require
函数,也就是localRequire
函数
function require(id) {
// 数组的解构赋值
const [fn, mapping] = modules[id];
function localRequire(name) {
return require(mapping[name]);
}
const module = { exports: {} };
fn(localRequire, module, module.exports); // 递归挪用
return module.exports;
}
吸收一个模块id,历程以下:
第一步:解构module(数组解构),猎取fn和当前module的依靠途径
第二步:定义引入依靠函数(相对援用),函数体同样是猎取到依靠module的id,localRequire 函数传入到fn中
第三步:定义module变量,保留的是依靠模块导出的对象,存储在module.exports中,module和module.exports也传入到fn中
第四步:递归实行,直到子module中不再实行传入的require函数
要更好相识“打包”的道理,就须要进修“模块化”的学问。
参考: