Uncaught ReferenceError: Cannot access '__WEBPACK_DEFAULT_EXPORT__' before initialization

Viewed 41005

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;
9 Answers

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.

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 of the store. Moving the import store from ./store upwards resolved this issue for me.

Try fixing the order of imports in your files.

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.

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"

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

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.

circular-dependency-plugin@5.2.2 works on webpack 4 apparently, and I can confirm it works on webpack@5.73.0 as well. Saved me lots of time :-) You can take it out of webpack dev config after it's done its work.

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

Solution - remove build/ directory and restart build.

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.

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.

Related