Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

215
Vistas
Is there any way to export a variable and change it after importing it?

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.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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);
  }
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda