Uncaught ReferenceError: Cannot access '__WEBPACK_DEFAULT_EXPORT__' before initialization - javascript

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;

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.

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.

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

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()

Have same issue in nextjs project.
Switching to previous versions or reinstalling node_modules/ - did not help.
Solution - remove build/ directory and restart build.

In my case, it was the entry-point file that used the following syntax:
export default <symbol>;

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.

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.

Related

Uncaught ReferenceError in DevTools for global variables [duplicate]

This question already has answers here:
How can I use modules in the browser, but also refer to variables and functions from within DevTools?
(4 answers)
Closed yesterday.
Update:
Looks like by importing another JS file and using the ES6 Modules, devtools compiles a bit different (will need to dive into learning more). The variables I thought were global were not in the module. Was able to fix this by assigning them to:
window.variable_name = variable_name
This allowed me to call the variables from devtools.
I have a project I am working on to practice a few JS skills. For the most part I have everything up and running but have come across an issue I can not seem to remedy.
I have an app.js file that is linked in my index.html. When running the live server from VS code everything works as it should, but when I open devtools to check some of the variables (global) & functions I get "Uncaught referenceError: variable_name is not defined" with a VM#:# reference.
Up to today, I have been able to call the variables from console without a problem.
I have 12 global variables, and all but 1 (submit) have this issue.
App.js:
import { autocomplete } from "./autocomplete.js";
// ######## GLOBAL VARIABLES ############
//------- Selectors ----------
const container = document.querySelector('.search-container');
const searchElement = document.getElementById('search');
const searchInput = document.querySelector('input[name="search-bar"]');
const submit = document.getElementById('search-bar');
const loader = document.querySelector('.loader');
const results = document.querySelector('.results');
const resetButton = document.querySelector('.reset');
const errorMessage = document.querySelector('.error');
const heart = document.querySelector('#favorite');
//------- Arrays & Objects ----------
let names = [];
let pokemon = {};
let bgImages = ["./resources/images/forest_background.jpg", "./resources/images/field.jpg", "./resources/images/galar-scenery.png", "./resources/images/night.jpg", "./resources/images/training.jpg", "./resources/images/poke-background.webp"];
//########## Grab & Store Pokemon Names for Autocomplete ##########
async function loadPokeNames() {
try {
const response = await fetch ('https://pokeapi.co/api/v2/pokemon?limit=250');
if (response.ok) {
const jsonResponse = await response.json();
// console.log(jsonResponse)
for (const poke of jsonResponse.results){
names.push(poke.name);
}
}
// throw new Error('Request Failed!')
} catch(error){
console.log(error);
}
}
//############ Search Function ###############
async function searchPokemon(e) {
e.preventDefault();
let pokeSearchValue = e.srcElement[0].value.toLowerCase();
searchElement.hidden = true;
loader.hidden = false;
try {
const pokeResponse = await fetch(`https://pokeapi.co/api/v2/pokemon/${pokeSearchValue}`);
if (pokeResponse.ok) {
const pokeJSON = await pokeResponse.json();
// Assign Values to Pokemon Object
pokemon.name = pokeJSON["name"];
pokemon.img = pokeJSON["sprites"]["other"]["official-artwork"]["front_default"];
pokemon.hp = pokeJSON["stats"][0]["base_stat"];
pokemon.attack = pokeJSON["stats"][1]["base_stat"];
pokemon.speed = pokeJSON["stats"][5]["base_stat"];
pokemon.defense = pokeJSON["stats"][2]["base_stat"];
pokemon.special_attack = pokeJSON["stats"][3]["base_stat"];
pokemon.special_defense = pokeJSON["stats"][4]["base_stat"];
console.log(pokemon);
createPokeCard(pokemon);
} else {
throw new Error("Something Went Wrong.");
}
} catch (error) {
loader.hidden = true;
errorMessage.hidden = false;
resetButton.hidden = false;
console.log(error);
}
}
// ####### Generates the Pokemon Card #########
function createPokeCard(object) {
const pokeName = document.querySelector('#poke-name p');
const pokeHP = document.querySelector('#hp');
const pokeImg = document.querySelector('#poke-image img');
const pokeAttack = document.querySelector('#attack .num');
const pokeSpeed= document.querySelector('#speed .num');
const pokeDefense = document.querySelector('#defense .num');
const pokeSpecialA = document.querySelector('#special-attack .num');
const pokeSpecialD = document.querySelector('#special-defense .num');
const backgroundImage = document.querySelector('#poke-image')
// Assign values to Results Card
backgroundImage.style.backgroundImage = `url('${bgImages[Math.floor(Math.random() * 6)]}')`;
pokeName.textContent = object.name;
pokeHP.textContent = `${object.hp} HP`;
pokeImg.src = object.img;
pokeAttack.innerText = object.attack;
pokeDefense.textContent = object.defense;
pokeSpeed.textContent = object.speed;
pokeSpecialA.textContent = object.special_attack;
pokeSpecialD.textContent = object.special_defense;
setTimeout(() => {
loader.hidden = true;
results.hidden = false;
resetButton.hidden = false;
}, 3000)
}
// ####### Resets Search & Card #########
function resetSearch() {
searchInput.value = '';
resetButton.hidden = true;
results.hidden = true;
searchElement.hidden = false;
errorMessage.hidden = true;
for (const att in pokemon){
delete pokemon[att];
}
}
//######## Favorite Functions ###########
function hoverFav() {
this.src = '../resources/images/heartline-fill.png';
}
function hoverOutFav() {
this.src = '../resources/images/heartline.png';
}
// ########### EVENTS ##############
window.onload = loadPokeNames;
autocomplete(searchInput, names)
heart.addEventListener('mouseenter', hoverFav);
heart.addEventListener('mouseout', hoverOutFav);
resetButton.addEventListener('click', resetSearch);
submit.addEventListener('submit', searchPokemon);
Linked (correct path) script tag:
<script src="./script/app.js" type="module"></script>
Any help or a point in the right direction would be amazing.
Tried calling global variables from devtools. Got an uncaught referenceError message.
Alright, so I have made a bit of digging around and it turns out the reason this happens is indeed because you're setting the type of the script as a module. Scripts that are run as modules are under strict mode by default, thus they don't allow access to global variables.
Also, they are made to run as a separate scripts(modules) and so any variables defined or imported into them are private by default and are not accessible to the global scope.
As for the error, in normal standard JS scripts, the access of a variable not defined properly(without let/const) will not throw an error, under strict mode however, it converts it into an error and throws it.
Take a look here for more info on differences between standard & module scripts. Also here for info on strict mode.

How to make conditional import work in React JS?

I have three pages in my react website that have the same layout and different content. I've made an array within a js file to map through the content, but I don't want to duplicate my code to another component.
The point is the I need the variable name to be the same, so I can map it.
I can get what I need with require matching the page url, but since I read it's not a good practice in react due to performance issues, I'm trying to accomplish it with import with no sucess though.
let pagedata = [];
if (matchpage1) {
pagedata = require("./data").page1data;
} else if (matchpage2) {
pagedata = require("./data").page2data;
} else if (matchpage3) {
pagedata = require("./data").page3data;
}
return (
pagedata.map((item) => {
I've read the react documentation, searched a lot, tried a lot of code, but nothing works if I try a simiçar aproach with import and lazy.
let pagedata = [];
if (matchpage1) {
pagedata = React.lazy(() => import('./pagedata1'));
} else if (matchpage2) {
pagedata = React.lazy(() => import('./pagedata2'));
} else if (matchpage3) {
pagedata = React.lazy(() => import('./pagedata3'));
}
What am I doing wrong?
Thank you so much for your attention.

Invariant Violation Invalid hook call / cross-origin error

So after making this function work I started to create a loop that would give me feedback from the backend after SSR, I wanted to use hooks so I made it a functional component and started to write but the hook (even with nothing in it) is throwing 2 errors. Invalid Hook Call and A cross origin error was thrown.
I tried changing the file name to jsx, moving the file out of the folder I had because there was a second node modules in there (I thought it was using two versions of React), I also read somewhere just to clear local storage and it was just a in development using localhost problem.
*Edit So i've found that its not even calling the fn: reactToPdfUtils.savePDFNOW(sourceElement, true, undefined, cb) its stopping here
//reactToPdf.js
import React, {useEffect} from 'react';
import { savePDF } from '#progress/kendo-react-pdf';
import { drawDOM, exportPDF } from '#progress/kendo-drawing';
var ClassInstancesStore = require('../libs/goggles/reflux/classInstances-store');
var ClassInstancesActions = require('../libs/goggles/reflux/classInstances-actions');
export const savePDFNOW = (sourceElement, willSaveToDB, pageTemplate, cb) => {
//this hook broke the program as soon as i put it in even with nothing inside
useEffect(() => {
//Functionthat gets called after sending the pdf to the backend
// function onClassInstancesStoreChange(opInfo){
// var e = cloneDeep(opInfo);
// if (e.op === 'Call::StorePassportPDFToDisk') {
// if(e.error){
// console.log(e.ret)
// setPdf({ pdfErrors: e.ret })
// } else {
// console.log(e.ret)
// setPdf({ inProgress: true })
// alert('Successfully created: ' + e.ret.fileName)
// // onSubmit()
// }
// }
// };
// let listeners = [];
// listeners.push(ClassInstancesStore.listen(onClassInstancesStoreChange));
// return function cleanup() {
// _.each(listeners, function(listener) {listener();}); //NOTE: destroy listeners
// }
}, [])
try {
//do all the my functions that make my pdf perfect
} catch (error) {
//snap something went wrong all my awesome error handling
}
};
//previewer.jsx
var React = require('react');
var _ = require('underscore');
var reactToPdfUtils = require('../../../../../components/reactToPdf.js');
handleSave = (sourceElement) => {
reactToPdfUtils.savePDFNOW(sourceElement, true, undefined, cb)
function cb(sendDataContent){
if(sendDataContent.err){
console.log(sendDataContent.message)
} else {
console.log('sucess')
}
}
};
My understanding of the code is that the function handleSave will call the external hook savePDFNOW. If this is what happens, then this will break regardless of the useEffect logic.
The reason for that is that hooks that are extracted outside of the component require their name to start with use
So to allow the hook to run you change its name to useSavePDFNOW.
That being said, I believe this is not a valid use case for useEffect, think of useEffect as componentDidMount/Update. This is relevant to component render cycle rather than event listeners. It makes more sense to do away with the useEffect and keep it a regular function.
A few more things, if you are using the latest react version you don't need to import react. Also it's recommended to use const/let instead of var as well.

React / ES6 - Efficiently update property of an object in an array

I am looking for the most efficient way to update a property of an object in an array using modern JavaScript. I am currently doing the following but it is way too slow so I'm looking for an approach that will speed things up. Also, to put this in context, this code is used in a Redux Saga in a react app and is called on every keystroke* a user makes when writing code in an editor.
*Ok not EVERY keystroke. I do have debounce and throttling implemented I just wanted to focus on the update but I appreciate everyone catching this :)
function* updateCode({ payload: { code, selectedFile } }) {
try {
const tempFiles = stateFiles.filter(file => file.id !== selectedFile.id);
const updatedFile = {
...selectedFile,
content: code,
};
const newFiles = [...tempFiles, updatedFile];
}
catch () {}
}
the above works but is too slow.
I have also tried using splice but I get Invariant Violation: A state mutation
const index = stateFiles.findIndex(file => file.id === selectedFile.id);
const newFiles = Array.from(stateFiles.splice(index, 1, { ...selectedFile, content: code }));
You can use Array.prototype.map in order to construct your new array:
const newFiles = stateFiles.map(file => {
if (file.id !== selectedFile.id) {
return file;
}
return {
...selectedFile,
content: code,
};
});
Also, please consider using debouncing in order not to run your code on every keystroke.

Websockets in Sapper

I have a readable store in Svelte that looks like this:
const state = {};
export const channels = readable(state, set => {
let st = state;
let socket = new WebSocket("ws://127.0.0.1:5999");
socket.onmessage = function (event) {
var datastr = event.data.split(':');
st[datastr[0]].value = datastr[1];
st[datastr[0]].timestamp = Date.now();
set(st)
};
return () => {
socket.close()
}
});
When I import it to my Svelte App works. But if I put that App.svelte as my index.svelte running on Sapper, it doesnt work at first. It says error 500 websocket is not defined. Once I reload the page in the browser start to work...
I have try to parse a function that creates the store instead:
export const getChannel = () => {
// here my store
return {...store}
}
and then creating the store inside a onMount() like this:
onMount( ()=> {
const channel = getChannel();
});
But doesnt seem to do the trick... What do I miss?
Note: If a just replace the store by a simple writable, and create the websocket onMount(), it works without any problem. I just only wanted to put all the communication inside the store as a readable...
In Sapper, code in components (or imported into components) is executed in Node during server-side rendering unless it's put inside onMount (which doesn't run on the server, because there's no 'mounting' happening) or an if (process.browser) {...} block, or something equivalent.
That includes things like references to $channels causing channels.subscribe(...) to be called during initialisation.
Since there's no WebSocket global in Node, creating that subscription will fail. The simplest workaround is probably a simple feature check:
const state = {};
export const channels = readable(state, (set) => {
if (typeof WebSocket === 'undefined') return;
let st = state;
let socket = new WebSocket("ws://127.0.0.1:5999");
socket.onmessage = function (event) {
var datastr = event.data.split(":");
st[datastr[0]].value = datastr[1];
st[datastr[0]].timestamp = Date.now();
set(st);
};
return () => {
socket.close();
};
});

Categories

Resources