Bootcamp
Search…
1.10: Multi-File Refactor

Introduction

When writing JavaScript for the browser we have the option of splitting code across multiple logical components or files to manage application complexity. These logical components will differ depending on the project. As our applications get more complex we'll split our code into smaller and smaller components.

Example

For example, index.html may import multiple JS files, each representing a different logical component of our app.
1
<script src="globals.js"></script>
2
<script src="gameInit.js"></script>
3
<script src="gamePlay.js"></script>
Copied!
  • The browser reads these files one at a time in the order the script tags appear in the HTML.
  • Once they are all loaded these files act as if you combine them together and run them.
  • All values available in one file are available in another.

Sample globals.js

1
const PI = 3.14;
2
​
3
// this will error. the browser hasn't read gameInit.js yet.
4
console.log(playerTurn);
Copied!

Sample gameInit.js

1
// PI is accessible because index.html imports globals.js before gameInit.js.
2
console.log(PI);
3
​
4
let playerTurn = 1;
Copied!

Exercise

Split one of your programs into at least two files. Paste the code below into your repo's eslintrc.js file if eslint keeps changing let to const when you don't want it to.
1
options: {
2
'prefer-const': ['error', {
3
destructuring: 'any',
4
ignoreReadBeforeAssign: false,
5
}],
6
},
Copied!