Work with stuff in other files in vanilla JS

Pere Sola - Aug 19 '21 - - Dev Community

I am reading again You Don't know JS by Kype Simpson and I wanted to write about something that I always forget: how to work with multiple files in vanilla JS. I am so used with writing React that when I do womething with vanilla JS I always need to Google this topic. You have two options. For both, we will be using the following structure:

index.html
script-one.js
script-two.js

  1. Adding all .js files in the <script></script> tags in the html

You can list all the .js files in the script tag in the html file. This may be fine if you are working with one or two files, but not if you have more files or are constantly adding files as it will be tedious to be adding them by hand. In any case, this is how it works:

  <body>
    <div>
      <button id="but-click">Click me</button>
      <section id="hello"></section>
    </div>
    <script src="script-one.js"></script>
    <script src="script-two.js"></script>
  </body>
Enter fullscreen mode Exit fullscreen mode

Whatever variable you have defined in script-one.js will be available in script-two.js and viceversa.

  1. Adding the entry point .jsfile in the html file and adding type="module"

The other option, recommended if your target browser supports it, is to only add the .js entry point file and add the type="module" property inside the script tag.

  <body>
    <div>
      <button id="but-click">Click me</button>
      <section id="hello"></section>
    </div>
    <script src="script-one.js" type="module"></script>
  </body>
Enter fullscreen mode Exit fullscreen mode

Then, in script-two.js you need to export the variable, like export const phrase = "How are you?". You import it in script-one.js like import { phrase } from "./script-two.js"; and phrase will be available for you to use in script-one.js.

It is all explained in this MDN article by the way!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .