Local variables and chunk splitting
Unanswered
Birman posted this in #help-forum
BirmanOP
Hey y'all, I'm sure what I'm doing here is not typically advised, but I have a pattern in a codebase that's shared between next.js and react-native where a few utility files get "initialized" by declaring a variable, then having a function set the variable that gets used throughout the file. For example, our logging writes to local storage on the web, and AsyncStorage in react-native, so that file looks something like:
This works great in react-native, and works great in dev, but I'm noticing in production this
I've got a couple of solutions I could go for, but wanted to see if anyone else had ran into this or has recommendations.
1. Set it to a key on
2. Modify the webpack config's
Any input would be much appreciated!
let storage: Storage | undefined
export function initializeLogging(s: Storage) {
storage = s
}
export function log(...data) {
if (storage) {
storage.append(data)
}
console.log(data)
}This works great in react-native, and works great in dev, but I'm noticing in production this
utils/log.ts file gets duplicated across multiple chunks, so pages/index.ts has its own version of it, and pages/settings.ts or whatever also has it. Which means that even if the pages/index.ts bundle ran initializeLogging, the settings bundle won't write to storage when it logs.I've got a couple of solutions I could go for, but wanted to see if anyone else had ran into this or has recommendations.
1. Set it to a key on
globalThis instead of a local variable. This pollutes the window object though, which I don't love.2. Modify the webpack config's
splitChunks configuration to ensure that files that adopt this pattern only ever exist in a single chunk. This seems ideal since it means no code changes aside from the config, but I've seen many people warded off from tinkering with this.Any input would be much appreciated!