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
- 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>
Whatever variable you have defined in script-one.js
will be available in script-two.js
and viceversa.
- Adding the entry point
.js
file in the html file and addingtype="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>
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!