[英]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.