[英]webpack/babel : what is the best way to share variables between bundles?
I have 2 separate js bundles that load on the same html page, so webpack.config.js:我有 2 个单独的 js 包加载在同一个 html 页面上,所以 webpack.config.js:
entry: {
preload: "./preload.tsx",
main: "./index.tsx"
}
GOAL: preload.js produces a Promise of a cache table that needs to be accessed by main.js.
目标:preload.js 生成需要由 main.js 访问的缓存表的 Promise。
But they need to be separate bundles, so import
won't work which will lead to execution of preload.js twice.但是它们需要是单独的包,因此
import
不起作用,这将导致 preload.js 执行两次。 I've tried to:我试图:
Uncaught ReferenceError: global_variable is not defined
Uncaught ReferenceError: global_variable is not defined
(window as any)
which looks evil(window as any)
它看起来很邪恶 I couldn't find a decent solution as of TypeScript 3.9.从 TypeScript 3.9 开始,我找不到合适的解决方案。 Any suggestions will be appreciated.
任何建议将不胜感激。
Like @Elias mentioned in a comment I think a prefer solution is a dynamic import one, but to answer the Question, You can do one of two things :就像评论中提到的@Elias 一样,我认为首选解决方案是动态导入解决方案,但要回答问题,您可以做以下两件事之一:
1. Use ProvidePlugin : 1.使用提供插件:
plugins: [
new webpack.ProvidePlugin({
globalVar: path.resolve(path.join(__dirname, 'src/GlobalVarModule'))
});
]
GlobalBarModule.ts: GlobalBarModule.ts:
var globalVar = "my global var value"
module.exports = globalVar;
And simple usage: Index.js:和简单的用法:Index.js:
console.log(globalVar);
Whenever the identifier (
globalVar
) is encountered as free variable in a module, the module is loaded automatically and the identifier is filled with the exports of the loaded module (or property in order to support named exports).每当标识符(
globalVar
)在模块中作为自由变量遇到时,模块会自动加载,并且标识符会填充加载模块的导出(或属性以支持命名导出)。
-From Docs. -来自文档。
2. Use Externals to let webpack know your are consuming a variable from the window: 2.使用Externals让 webpack 知道您正在使用 window 中的变量:
externals: {
globalVar: path.resolve(path.join(__dirname, 'src/GlobalVarModule'))
}
Somewhere early in your code:在您的代码早期的某个地方:
globalVar = "my global var value";
Usage:用法:
import globalVar from 'globalVar';
console.log(globalVar);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.