- Webpack 获取您指定的所有文件并将它们合并到一个大输出文件中,以便在正确的时间、正确的范围内拉入相关模块。
如果我们有:
// sum.js
var sum = function (a, b) {
return a + b;};
// multiply.js
// slightly contrived here - we're going to repeatedly sum to multiply, to illustrate dependency
// interaction
var multiply = function (a, b) {
var total = 0;
for (var i = 0; i < b; i++) {
total = sum(a, total);
}
return total;
};
// index.js
- our application logic
var totalMultiply = multiply(5, 3);
var totalSum = sum(5, 3);
console.log('Product of 5 and 3 = ' + totalMultiply);
console.log('Sum of 5 and 3 = ' + totalSum);
// index.html
- our entry point to our application
<html>
<head>
<script src="src/sum.js"></script>
<script src="src/multiply.js"></script>
<script src="src/index.js"></script>
</head>
</html>
这样的输出将是:
Product of 5 and 3 = 15
index.js:17 Sum of 5 and 3 = 8
- 如果我们在 index.html 中的顺序错误,我们的应用程序将无法运行。如果 index.js 包含在任何其他依赖项之前,或者 sum.js 包含在 multiply.js 之后,我们将得到错误。这就是捆绑文件的重点。
- Webpack 可以将我们所有的依赖项拉到一个文件中
bundle file,这意味着只需要下载一个依赖项。
2- 使依赖项可用并链接它们
- CommonJS 使用 module.exports 将函数或变量导出或提供给其他代码。它使用 require 然后拉入这些导出的值。
// sum.js
var sum = function (a, b) {
return a + b;
};
module.exports = sum;
//乘法.js
var sum = require('./sum');
var multiply = function (a, b) {
var total = 0;
for (var i = 0; i < b; i++) {
total = sum(a, total);
}
return total;
};
module.exports = multiply;
// index.js
- our application logic
var multiply = require('./multiply');
var sum = require('./sum');
var totalMultiply = multiply(5, 3);
var totalSum = sum(5, 3);
console.log('Product of 5 and 3 = ' + totalMultiply);
console.log('Sum of 5 and 3 = ' + totalSum);
- 请注意,我们已将 sum 和 multiply 提供给其他代码,并且我们已在 multiple.js 和 index.js 中引入了这些导出的函数。
- 还要注意,我们的 index.html 现在只需要拉入一个文件 - bundle.js。
- 我们可以公开我们想要的内容并使其他代码有效地保密
这就是重点,你需要告诉 webpack 你需要哪些模块来相互通信和共享数据。与 webpack 中一样,每个模块的表面积都比完整程序小,这使得验证、调试和测试变得微不足道。编写良好的模块提供了可靠的抽象和封装边界,因此每个模块在整个应用程序中都具有连贯的设计和明确的目的。
- 我们还将网络调用从 3 个(sum.js、multiply.js 和 index.js)减少到
一次调用 - 这将有助于加快加载时间。
请注意,除非您确实需要它,否则我不建议将库或模块公开为全局,即模块系统的重点是显式声明依赖项。
- ProvidePlugin:此插件使模块可作为每个模块中的变量使用。仅当您使用该变量时才需要该模块。
示例:在每个模块中都可以使用 $ 和 jQuery,而无需编写 require("jquery")。
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery"
})
所以:
// app.js
$.ajax(...);
被有效地转译成:
// app.js
require('jquery').ajax(...);
webpack 将生成一个加载指定模块的代码,就像它为 import 或 require 所做的一样。