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

84 views Asked by At

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:

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?

1

There are 1 answers

1
Sebastian On BEST ANSWER

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;