accessing changed value of exported variable

The functionality you're expecting can't be observed with a default export, as already explained, but it will occur with a named export (unfortunately):

// a.js
export let test = null;

export function change() {
  test = "test";
  console.log(["in a.js change()", test]);
}
console.log(["in a.js global", test]);

and

// b.js

import { test, change } from "./a.js";

console.log(["in b.js, pre a.change()", test]);
change();
console.log(["in b.js, post a.change()", test]);

Here, the imported test changes, because it's a named import.

https://codesandbox.io/s/nice-liskov-se4fh

This sort of behavior is very unintuitive, because to the consuming module, it kind of looks like what seemed to be a primitive magically reassigns itself, which looks crazy from any other context of Javascript. This is why it's often recommended never to reassign exported variables. Use a different method, like the ones in jfriend00's answer.


Aren't these variables being imported as reference? Meaning, they should reflect any changes made to them at a later point in runtime.

No. When you imported the variable, you made a copy of it into a new variable. That copy will not change if the original variable gets something new assigned to it.

When you do this:

import test, { change } from './a.js'

You're assigning the exported default value into a new variable named test. That new variable has no connection with the other variable any more.

There are several ways to provide access to the changed variable:

  1. Export an object where the variable is a property on that object. Then, in your original module, change the value of that property. In this case, the imported module will have a pointer to the same object so when you access the property on that object, you will see the new value.

  2. Export a method that retrieves the current value of the variable from within the module.

  3. Create an event which an outside module can listen for and fire that event anytime the value of the variable changes.

Remember that plain values are assigned by making a copy of the value and inserting it into the new variable. Objects, on the other hand, are assigned by making a copy of the pointer to the same object and putting that pointer into the new variable. So, with objects the new variable contains a pointer to the same object.