Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Variable becomes a constant when imported into another js file in vite

I’m working in a vanilla JS project with vite and I find the following error:

I have an app.js file where I initialize a variable with the command let and I export it

let activePoint = null;
export { activePoint };

Then I have another JS file (tool.js) where I import the variable using:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import { activePoint } from '../js/app.js'

When I try to modify said variable (for example: activePoint=4;) in the file tool.js, I get the error Uncaught TypeError: Assignment to constant variable.

I have tried both let and var, and there is no difference in behavior. Also tried to initialize and export in one line vs two, but makes no difference either. Is there some Vite behavior that I am missing that transforms variables to constants?

>Solution :

From MDN:

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 re-assigned by the importing module.

So if you really need to work with something mutable, you need to export an object. The reference will again be immutable, but you will be able to change its properties. E.g.

export const obj = {activePoint: null}

and in tool.js

import {obj} from '../js/app.js';
obj.activePoint = 4;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading