Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
127
rated 0 times [  130] [ 3]  / answers: 1 / hits: 41775  / 6 Years ago, tue, january 9, 2018, 12:00:00

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 seems 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?


More From » import

 Answers
137
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.


[#55505] Saturday, January 6, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
austynp

Total Points: 505
Total Questions: 118
Total Answers: 106

Location: Tajikistan
Member since Sun, Aug 29, 2021
3 Years ago
austynp questions
;