[英]When using Webpack and Babel, what is the best way to turn off compression?
[英]webpack/babel : what is the best way to share variables between bundles?
我有 2 個單獨的 js 包加載在同一個 html 頁面上,所以 webpack.config.js:
entry: {
preload: "./preload.tsx",
main: "./index.tsx"
}
目標:preload.js 生成需要由 main.js 訪問的緩存表的 Promise。
但是它們需要是單獨的包,因此import
不起作用,這將導致 preload.js 執行兩次。 我試圖:
Uncaught ReferenceError: global_variable is not defined
(window as any)
它看起來很邪惡從 TypeScript 3.9 開始,我找不到合適的解決方案。 任何建議將不勝感激。
就像評論中提到的@Elias 一樣,我認為首選解決方案是動態導入解決方案,但要回答問題,您可以做以下兩件事之一:
1.使用提供插件:
plugins: [
new webpack.ProvidePlugin({
globalVar: path.resolve(path.join(__dirname, 'src/GlobalVarModule'))
});
]
GlobalBarModule.ts:
var globalVar = "my global var value"
module.exports = globalVar;
和簡單的用法:Index.js:
console.log(globalVar);
每當標識符(
globalVar
)在模塊中作為自由變量遇到時,模塊會自動加載,並且標識符會填充加載模塊的導出(或屬性以支持命名導出)。
-來自文檔。
2.使用Externals讓 webpack 知道您正在使用 window 中的變量:
externals: {
globalVar: path.resolve(path.join(__dirname, 'src/GlobalVarModule'))
}
在您的代碼早期的某個地方:
globalVar = "my global var value";
用法:
import globalVar from 'globalVar';
console.log(globalVar);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.