-1

I have a NextJS app with some server side code that gets bundled with Webpack (default NextJS setup). When running this with the product build, I get the following error:

ReferenceError: Cannot access 'providers' before initialization

Looking at the generated bundle at the lines referenced by the error, I can see this:

const providers = {
    [_myapp_webapp_types__WEBPACK_IMPORTED_MODULE_0__.ProviderType.Provider0]: _provider0__WEBPACK_IMPORTED_MODULE_1__/* .provider0 */ .d,
    [_myapp_webapp_types__WEBPACK_IMPORTED_MODULE_0__.ProviderType.Provider1]: _provider1__WEBPACK_IMPORTED_MODULE_2__/* .provider1 */ .S
};
function getProvider(config) {
    return providers[config.type];
}

In my head, there can be nothing stopping providers from being initialised when the getProvider function is called. What is going on here, and what can I do about it?

EDIT: The code is within a separate file that gets imported by another file that calls the getProvider-function. This means (in my head) that the providers variable without doubt should be initialised as soon as the function is called (from outside the module).

(Also, everything works just fine when running locally)

Sten
  • 1,079
  • 11
  • 25
  • 1
    You're probably accessing `providers` somewhere earlier in your code, see https://stackoverflow.com/questions/33198849/what-is-the-temporal-dead-zone , or calling `getProvider` before initializing `providers`. – Teemu Mar 10 '22 at 08:34
  • The error message points to that exact line (`return providers[config.type];`). So I do not think so. – Sten Mar 10 '22 at 08:37
  • 1
    Why shouldn't the function be called before providers is initialized? In my head you can call the function from any place before the init code of the providers array – Thallius Mar 10 '22 at 08:37
  • Ah, sorry, yes, but that code is the only code in that file. So as soon as the file is imported the providers const should be initialised. And only after that can the function be called. – Sten Mar 10 '22 at 08:39
  • Seems more like webpack is doing some magic with dynamic imports. Is there a way to turn off that server side? I don't see the purpose of having that (if true...). – Sten Mar 10 '22 at 08:43
  • Yes, using Webpack (or any other javascript deployment tool) is a mess with pure javascript. For me it looks like they are all only tested with react, angular and such monster frameworks. – Thallius Mar 10 '22 at 09:10

1 Answers1

0

Turns out the problem was solved by updating to the latest minor upgrade of NextJS. (So this was possibly a bug somewhere down the line.)

Sten
  • 1,079
  • 11
  • 25