Uncaught ReferenceError: Cannot access '__WEBPACK_DEFAULT_EXPORT__' before initialization
Asked Answered
P

16

76

I have a problem with my webpack project, so I was trying to import one class to another and instantiate it but suddenly an error appear in my console and my program stopped working, it was this:

Uncaught ReferenceError: Cannot access '__WEBPACK_DEFAULT_EXPORT__' before initialization

This is the code of the class were I am trying to import my another class (that is PopUpPlugin):

import PopupPlugin from './popupPlugin.js';

export const addSearchBtnEvent = (weatherUI) => {
  const searchBtn = document.querySelector('.weather__search');
  
  searchBtn.addEventListener('click', () => {
    weatherUI.style.opacity = '1';
    weatherUI.style.visibility = 'visible';
  })
}

export const addSearchExitEvent = (weatherUI) => {
  const weatherExit = document.querySelector('.weather__search-exit');
  
  weatherExit.addEventListener('click', () => {
    weatherUI.style.opacity = '0';
    weatherUI.style.visibility = 'hidden';
  })
}

const popupObj = new PopupPlugin();

class searchDashboard {
  constructor() {
    
  }
  
  setInputEvent() {
    const inputSearch = document.querySelector('.weather__city-search');
    const inputSearchBtn = document.querySelector('.weather__search-btn');
    
    inputSearchBtn.addEventListener('click', () => {
      const inputSearchVal = inputSearch.value;
      
      this.validateStr(inputSearchVal);
    });
  }
  
  validateStr() {
    const onlyLettersAndSpaces = /^[a-zA-Z][a-zA-Z\s]*$/;
    
    if(str.trim().length > 0 && str.match(onlyLettersAndSpaces)) {
      const strValue = str.toLowerCase().trim().replace(' ', '+');
      
      this.popupObj.searchCoincidences(strValue, 'weather__search-ui');
    }
  }
}

export default searchDashboard;

I don't actually know why this is happening, I also tried to instantiate it inside the constructor and it worked but it sended me the error of an stack overflow.

PD: If someone needs it here is the code of the PopupPlugin. (Here is what was working to me that was instantiating the class inside the constructor until the stack overflow error appeared)

import ManageWeatherDashboard from './manageWeatherDashboard.js';
import { getFetch, repeatAppend } from './weatherHelpers.js';

class popupPlugin {
  constructor() {
    this.manageWeatherDashboardObj = new ManageWeatherDashboard();
  }

  validateStr(str) {
    const onlyLettersAndSpaces = /^[a-zA-Z][a-zA-Z\s]*$/;
    
    if(str.trim().length > 0 && str.match(onlyLettersAndSpaces)) {
      const strValue = str.toLowerCase().trim().replace(' ', '+');
      
      return strValue;
    }
  }
  
  searchCoincidences(val, parent) {
    getFetch(`https://www.metaweather.com/api/location/search/?query=${val}`)
      .then(res => res.text())
      .then(data => {
        const parentResults = document.querySelector('.'+parent);
        
        parentResults.innerHTML = '';
        
        const dataArr = JSON.parse(data)
        
        if(dataArr.length >= 15) {
          let resVal;
          
          for(let i = 0; i <= 15; i++) {
            resVal = this.addDOMResultCoincidences(parent, dataArr[i].title,
              dataArr[i].woeid);
          }
          
          this.whenClickCoincidence(resVal);
        } else {
          let resVal;
          
          dataArr.forEach(el => {
            resVal = this.addDOMResultCoincidences(parent, el.title, el.woeid);
          })
          
          this.whenClickCoincidence(resVal);
        }
        
      })
  }
  
  addDOMResultCoincidences(parentBlock, name, id) {
    const args = Array.from(arguments);
    
    if(args[0] === 'popup__results') {
      const popupResults = document.querySelector('.popup__results');

      const divResult = document.createElement('div');
      divResult.className = 'popup__result';
      divResult.setAttribute('data-woeid', id);
      
      const spanResultName = document.createElement('span');
      spanResultName.className = 'popup__result-name';
      
      const cityReturn = document.createTextNode(args[1]);
      
      spanResultName.appendChild(cityReturn);
      
      divResult.appendChild(spanResultName);
      
      popupResults.prepend(divResult);
      
      return divResult;
    }
    
    if(args[0] === 'weather__search-ui') {
      const weatherUI = document.querySelector('.weather__search-ui');
      
      const divResult = document.createElement('div');
      divResult.className = 'weather__search-result';
      divResult.setAttribute('data-woeid', id);
      
      const spanResultName = document.createElement('span');
      const spanResultNameText = document.createTextNode(args[1]);
      spanResultName.className = 'weather__city-result';
      spanResultName.appendChild(spanResultNameText);
      
      const iconResult = document.createElement('i');
      iconResult.className = 'fa fa-arrow-right weather__go-result';
      
      repeatAppend([spanResultName, iconResult], divResult);
      
      weatherUI.appendChild(divResult);
      
      return divResult;
    }
  }
  
  // When click a coincidence in search field
  
  whenClickCoincidence(el) {
    const woeId = el.getAttribute('data-woeid');
    
    el.addEventListener('click', () => {
      let handler = 0;
      
      if(handler === 0) {
        getFetch(`https://www.metaweather.com/api/location/${woeId}/`)
          .then(res => res.json())
          .then(data => {
            const popup = document.querySelector('.popup');
            
            const weatherNext6Days = data.consolidated_weather;
            
            this.manageWeatherDashboardObj.changeWeatherBar(weatherNext6Days[0], data.title);
            
            weatherNext6Days.slice(1, 6).forEach(el => {
              this.manageWeatherDashboardObj.nextFiveDays(el);
            })
            
            this.manageWeatherDashboardObj.updateStadistics(weatherNext6Days[0]);
            
            popup.style.opacity = '0';
            popup.style.visibility = 'hidden';
          })
      }
      
      handler += 1;
    })
  }
}

export default popupPlugin;
Presume answered 27/11, 2020 at 13:32 Comment(4)
Which version of Webpack are you using?Ecstasy
Sorry for leaving this comment inactive, i have the most recent version in npm 5.12.0Presume
How do you run Webpack? Via CLI? Via npm run? Any other?Asquith
I run webpack via cli.Presume
G
72

This might be caused by a cyclic dependencies (i.e. moduleA imports module B and vice versa at the same time). Take a deeper look at your code.

Gilcrest answered 30/9, 2021 at 17:30 Comment(2)
I had this problem and it was a matter of circular dependenciesKallman
Same here. Plus, I want to add (unfortunately edit queue is full) that the cyclic dependency might not be anywhere nothing recent you've done. I spent some time commenting-out code until I found that the module that was causing it was there from the beginning and long before the problem arised. Also in the stack trace of the problem you might find a reference to the module that is causing it even if it is through its index file.Gramme
M
18

I faced the same issue when I moved the import statement for the redux store below some import of a local module that was dealing with some reducer reference from the store. Moving the import store from ./store upwards resolved this issue for me.

Try fixing the order of imports in your files.

Medial answered 2/2, 2021 at 11:35 Comment(2)
FWIW my issue was instantiating a singleton based on a imported modules. Similar to your suggestion, it was fixed by moving instantiation of singleton to a check within a function call to get the singleton.Rooted
Thanks! It does work for the same problemFreespoken
E
15

Had this problem, after upgrading from webpack 4 to webpack 5, and, yes, it was a circular dependency in my case.

Furthermore I found this blog How to Eliminate Circular Dependencies from Your JavaScript Project which led me to https://github.com/aackerman/circular-dependency-plugin

Plopped the plugin into my webpack dev config, as per sample on github, then spent some time reading its output figuring out where I went wrong. Fixing things was pretty easy once I knew the problem - it had been a pretty basic error.

[email protected] works on webpack 4 apparently, and I can confirm it works on [email protected] as well. Saved me lots of time :-) You can take it out of webpack dev config after it's done its work.

Ending answered 11/8, 2022 at 7:18 Comment(0)
M
5

In my case, it was due to circular import. Meaning, that two modules are exporting and importing contents form each other

Melanous answered 21/11, 2022 at 16:5 Comment(0)
I
4

For anyone whose issue is not a circular dependency, it could also be a missing import.

In my case, using Material UI 5, I forgot the line import { styled } from "@mui/styles";, which gave me this error:

Uncaught ReferenceError: Cannot access '__WEBPACK_DEFAULT_EXPORT__' before initialization

instead of the usual ReferenceError: MyModule is not defined missing import error.

Ilario answered 20/2, 2022 at 7:48 Comment(0)
F
3

Using my IDE auto import I had something like:

import useStore, { useCart } from "../lib/store"

Everything was working fine for awhile! But then I got the same error until I changed my import to be like this:

import { useStore, useCart } from "../lib/store"
Faux answered 13/2, 2022 at 10:1 Comment(0)
H
3

In my case this was caused by importing from a common index.ts file where the affected object is also exported.

For example say my ./widgets/index.ts looked like:

export { WidgetA } from './widgets/object-a';
export { WidgetB } from './widgets/object-b';

And in ./widgets/object-b.ts this would cause the Webpack error:

import { WidgetA } from '../widgets';

However this would work:

import { WidgetA } from '../widgets/object-a';
Himes answered 1/3, 2023 at 16:45 Comment(2)
Thank you so much! You saved my day! This issue looks quite weird, do you know why the 1st example doesn't work (with ./) while the 2nd (with ../) does?Otherwhere
My guess is that it's still a circular dependency thing, but its obscured by the transpiler. I've noticed this issue in NextJS when mixing Server Side and Client Side code, and in Storybook, both of which transpile in their own weird way. @OtherwhereHimes
L
2

in my case, I was just trying to call the dispatch function before the store had fully loaded - i.e. store.dispatch()

Lovejoy answered 11/6, 2022 at 13:8 Comment(0)
T
1

I also hit this problem, caused by circular component reference - Component A includes component B which includes component A. (A->B->C->A in my case)

The solutioin is in the Vue documentation (Vue.js 2 in my case) Circular References Between Components

Second proposed decision fix my case:

components: {
   circularComponent: () => import('./CircularComponent.vue)
}
Tabulate answered 24/10, 2023 at 12:53 Comment(0)
M
0

Have same issue in nextjs project. Switching to previous versions or reinstalling node_modules/ - did not help.

Solution - remove build/ directory and restart build.

Malapert answered 22/8, 2022 at 11:59 Comment(0)
M
0

In my case, it was the entry-point file that used the following syntax:

export default <symbol>;
Mazzard answered 26/10, 2022 at 22:40 Comment(0)
N
0

in my case, inside the store/test/fetchSmth.saga.ts file, I was trying to import a function not from the store.

just moving this function to the store/test/utils.ts file helped me.

Nummary answered 4/7, 2023 at 14:22 Comment(0)
D
0

This is error also can be occur by not clearing the export. export default componentsname => so also check the all files component name is right as component name or not.

Dixie answered 3/9, 2023 at 5:34 Comment(2)
Welcome to Stack Overflow! Please phrase this as an explained conditional answer, in order to avoid the impression of asking a clarification question instead of answering (for which a comment should be used instead of an answer, compare meta.stackexchange.com/questions/214173/… ). For example like "If your problem is ... then the solution is to .... because .... ."Televisor
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Ganef
C
0

I actually experimented this, and to solve it, went from

const Field = () => {}

export default Field

to this

export default function Field () {}
Chamberlain answered 26/1 at 22:38 Comment(0)
P
-1

Maybe because you used circle import.

For me, I used encapsulated axios to request in mobx store, and I also used some data from mobx store in encapsulated axios.

Pileate answered 10/2, 2022 at 9:40 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Ganef
K
-2

This isn't exactly what's causing the same error to occur for me.

Mine were caused by calling things like useState, useEffect and firebase() outside the main functional Component Block. This is very dumb but I somehow completely missed it.

Hope it helps anyone from the future who had the same problem as mine.

Koressa answered 17/1, 2022 at 15:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.