简体   繁体   中英

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:

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.

But they need to be separate bundles, so import won't work which will lead to execution of preload.js twice. I've tried to:

  • add a global variable (couldn't figure out where the actual definition should go so Uncaught ReferenceError: global_variable is not defined
  • add an extra property to window obejct (couldn't figure out how to make it work with TypeScript 3.9. Tried pretty much everything here and more. The only thing that worked was (window as any) which looks evil
  • I don't want hacky workarounds like using LocalStorage or DOM manipulation.

I couldn't find a decent solution as of 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 :

1. Use ProvidePlugin :

plugins: [
   new webpack.ProvidePlugin({
      globalVar: path.resolve(path.join(__dirname, 'src/GlobalVarModule'))
   });
]

GlobalBarModule.ts:

var globalVar = "my global var value"
module.exports = globalVar;

And simple usage: 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).

-From Docs.

2. Use Externals to let webpack know your are consuming a variable from the 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM