[英]Why do i need to import modules everytime in webpack bundle?
我使用webpack生成捆绑文件,即app.bundle.js。 在每个单独的js文件中,似乎都需要导入将要使用的模块。
我一直在努力解决这个问题,但这使我难以捉摸。 简单来说,我理解捆绑过程的方式是:它将获取您指定的所有文件,并将它们合并为一个大输出文件。
那应该意味着一个类在该大文件中被声明为ONCE,并且应该足以作为所有其他类的引用。 为什么我应该一次又一次地导入它,而只是将其放在捆绑文件的顶部,即可用于此后编写的所有其他代码?
PS(一个简单的例子)
我有以下文件:
A.js
class A {
doIt(){
console.log(this);
}
}
B.js:
import {A} from "a.js";
class B extends A {
}
main.js:
import {A} from "a.js"
import {B} from "b.js"
要在main.js中使用B,我也需要导入A。 如果A还有另一个子类,我也需要导入它。 对我来说,这看起来很疯狂,以至于我希望将窗口上的所有内容都修复。
如果有人知道,请帮助我了解我所缺少的内容。
因此,如果我们有:
// 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
bundle file
,这意味着只需要下载一个依赖项即可。 2-使依赖项可用并链接它们
// sum.js
var sum = function (a, b) {
return a + b;
};
module.exports = sum;
//乘法
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);
这就是重点,您需要告诉webpack哪些模块需要它们相互通信和共享数据。 与webpack一样,每个模块的表面积都小于完整程序的表面积,从而使验证,调试和测试变得微不足道。 编写良好的模块提供了可靠的抽象和封装边界,因此每个模块在整个应用程序中具有一致的设计和明确的目的。
注意,除非您确实需要,否则我不建议将库或模块公开为全局,即模块系统的重点是显式声明依赖项。
示例:使$和jQuery在每个模块中可用,而无需编写require(“ jquery”)。
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery"
})
所以:
// app.js
$.ajax(...);
有效地转换为:
// app.js
require('jquery').ajax(...);
webpack会生成一个与指定模块相同的加载代码,与导入或需要加载该模块相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.