Explosion
Explosion

Reputation: 326

Is there a way to export an object while preserving variables in JavaScript?

So say I have one file (file1.js) with the following code:

var output = {
  thing: "A thing",
  another: "Another thing"
}

Now if I were to reference this in another file, like this:

<script src='file1.js'></script>
<script>
console.log(output);//Logs the object to the console.
</script>

it would import the output variable, for use. However if I were to use exports, as in the following snippet it would not work, and instead only allow imports:

//file1.js
var output = {
  thing: "A thing",
  another: "Another thing"
}
export default output;
<script type="module">
   import something from "file1.js";
   console.log(something.thing);//"A thing";
   console.log(output);//Error, but if I had omitted the exports and imports it would work fine.
</script>

Is there a way to make both of these work? So that I could import something from "file1.js" while still being able to use the "output" variable? Note that I'm using this in a library so I cannot rely on the user to do something client-side.

Upvotes: 0

Views: 40

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370779

It's possible, but I wouldn't recommend it in most cases: assign the exported object to the window first:

const output = {
  thing: "A thing",
  another: "Another thing"
};
window.output = output;
export default output;

Then you'll be able to use both window.output and the imported object.

But one of the main benefits of using modules is constrained scope and avoiding unnecessary global pollution, which is kind of defeated by explicitly polluting the global object.

It could make sense if this is done in only one place - like to assigning the whole library namespace to a single property on the window - but I'd hope not to see relying on global properties to be frequently relied on.

Upvotes: 1

Related Questions