Home > Software engineering >  Include a JS file directly in another?
Include a JS file directly in another?

Time:12-09

Let's say I have two JS files, which are both obviously representative of larger files. The first is root/foo.js:

let foo = true;

The next is root/foopolice.js. This code depends on root/foo.js, and by itself, it throws an error:

function patrol(){
  if (foo) alert("Found foo"); // ReferenceError

Finally, there is root/index.html, which links the two:

<script src="/foo.js"></script>
<script src="/foopolice.js"></script>
<button onclick="patrol()">Patrol for foo</button>

The question is, how would I "include" the variable defined in root/foo.js directly into root/foopolice.js without combining the two into one? The use of both script tags is not enough, because root/foopolice.js would still warn of a nonexistent error while I edit it. I'm open to solutions using JQuery or just vanilla JS, depending on best practice.

CodePudding user response:

Typically, a build process is used to create a JS bundle that would extract and combine all of the required code from multiple files (see Parcel or ESBuild).

Without a build process, modern JS modules (also known as "ES modules") could be imported using <script type="module">. JQuery can be avoided entirely in 2020 and beyond.

library.js

const name = 'Jane Doe'

export {
  name
}

main.js

import { name } from './library.js'

function sayHello() {
  console.log(`hello ${name}!`)
}

window.addEventListener('DOMContentLoaded', event => {
  document.querySelector('button').addEventListener('click', sayHello)
})

index.html

<script type="module" src="main.js"></script>

<button>Say Hello</button>
  • Related