In javascript(node JS), I have made a config.js file like below for export a name variable
Config.js
export let name ="ayush";
and I am importing the name variable in index.js file
index.js
import {name} from "./config.js";
name ="Rishabh"
console.log(name);
But I am getting Type Error:assignment to constant variable.
I have declared a variable as Let , then why still I am getting above error.
I am trying to change the variable name in another file. but I am getting the error, not able to understand what javascript concept is missing like (import is only read only).
2
Answers
Remember in your
index.js
file you are reassigningname
variable imported fromconfig.js
file which is not allowed.You should use an object instead of a primitive value, because properties of an object can be modified even when the object itself is imported as a constant.
Do this for
Config.js
Then do this for
index.js
Try this I hope it will work.
In JavaScript, imported bindings are read-only. You cannot change their value in the module where they are imported.
This is because exporting mutable variables can lead to unpredictable behavior and bugs.
If you want to share a common object, which also need to be mutable, export a const object and modify the properties of it instead.
config.js
index.js