34

I'm using ES6 modules and am importing a variable from moduleA into moduleB:

//moduleA.js
let a = 5;
let b;

export { a, b };

//moduleB.js
import { a, b } from './moduleA'

a = 6;
b = 1;

But on change/assignment in moduleB I'm getting error such as:

a = 6;

ReferenceError: a is not defined

On the other hand I can console.log(a) in moduleB.

It seams it is not possible to assign to imported variables? Is this true or am I missing the way to do it? Why is this not possible?

croraf
  • 2,926
  • 2
  • 22
  • 37
  • 5
    In ES6, imports are live read-only views on exported-values. https://stackoverflow.com/a/32558929/2894798 – Renzo Calla Jan 09 '18 at 13:00
  • @RenzoCC you should post an answer using that as a reference, as both questions are a bit different it's not a duplicate – GMaiolo Jan 09 '18 at 13:03
  • What misses there is to note that if a or b (in my example) is an object you CAN mutate it from any module. What you cannot do apparently is reassign a and b variables. Am I correct? – croraf Jan 09 '18 at 13:05

2 Answers2

53
import { a, b } from './moduleA'

is similar to

const a = ...
const b = ...

in that you cannot assign the value afterward. It's not quite the same because the values can change, but they can only be changed from inside the module. So you could do

let a = 5;
function setA(value) {
  a = value;
}

export { a, setA };

with

import { a, setA } from "./moduleA";

setA(4);
console.log(a); // 4

From outside of a module you can mutate a value, just like you could with const, like if you're changing a property on an object, but you cannot make the variable point to an entirely different object.

loganfsmyth
  • 135,356
  • 25
  • 296
  • 231
16

You can use an object instead of variables, like this the reference doesn't change :

//moduleA.js
let object = {
    a: 5,
};

export { object };

//moduleB.js
import { object } from './moduleA'

object.a = 6;
object.b = 1;
Troopers
  • 3,982
  • 1
  • 29
  • 52
  • Thanks. I'm already using this approach. Or as other answers noted use a setter function residing in moduleA. I think it is confirmed that there is restriction in reassigning other modules' exports. Don't know why other answers got deleted though. – croraf Jan 09 '18 at 16:29