0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you SO much!!! =) I'm only doing this for one variable and I don't want the user to have to use imports, but I want that to be an option.
it works fine when using import but when just doing script:src it does not work.
Scripts with import / export syntax must be modules. You must use <script type="module" src="...">. Even if the script consuming this one is not using import to take in the output variable, your library still needs to have type="module" on the HTML page. Either that, or make two separate versions of your library: one with ES6 modules, and one that assigns itself to the window.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.