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:
Uncaught ReferenceError: global_variable is not defined
(window as any)
which looks evilI 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.