I'm using Webpack, and I have a function.js
file with this code:
import { randomNum } from '../index.js';
export function getSlidePrev() {
if (randomNum > 1) {
randomNum -= 1;
setBg(randomNum);
}
}
And in my main.js
file I have this:
function getRandomNum(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min 1)) min;
}
export let randomNum = getRandomNum(firstSlideNumber, lastSlideNumber);
const slidePrev = document.querySelector('.slide-prev');
slidePrev.addEventListener('click', getSlidePrev);
I get this type of error:
Uncaught TypeError: Cannot set property randomNum of #<Object> which has only a getter
at HTMLButtonElement.getSlidePrev
I tried to google, but I couldn't solve this issue. Someone says it's because of using Babel.
CodePudding user response:
An imported variable is a read-only, you cannot modify it in the file where it's imported. Here is what mdn says about it:
The static
import
declaration is used to import read-only live bindings which are exported by another module. The imported bindings are called live bindings because they are updated by the module that exported the binding, but cannot be modified by the importing module.
You can turn randomNum
into an object if you want to mutate it across different imports. For that change it in index.js
to:
export const randomNum = {value : 1000};
And use it this way:
import { randomNum } from "../index.js";
export function getSlidePrev() {
if (randomNum.value > 1) {
randomNum.value -= 1;
setBg(randomNum.value);
}
}