Breaking the Code into Files
Objectives
Notes
- Our main HTML file is becoming messy.
- It would be nice to make some more manageable portions.
- The way to do this is to put the javascript code in different files.
- There are several methods for this, but the most modern is as follows
- copy newton.html main.js
- remove the html code from the js file
- Remove the js code from the html file
- Add
<script type="module" src="main.js"></script> to the html file, in the header probably
- This is using a fairly new java script function modules
- This eliminates the need to worry about order, or deferring execution, they are deferred automatically
- Apparently, they suggest using the extension .mjs for modules.
- I want to split the drawing routine into a drawing.js file
- I changed the name to be DrawImage
- I added parameter, the canvas
- The global variables are no longer available in included files.
- An alternative is to grab some of these values in the html file and mark them as var.
- This is in the HTML file, not main.js
- The first is probably the best, as we can reuse code.
- The second is minimally acceptable.
- I have examples of both in my code.
- To be able to use this function it needs to be
- Marked for export in the source code file (drawing.js)
export function DrawImage(...
- Imported in the main.js
import {DrawImage} from "./drawing.js"
- There are other ways to do this
- But this will work.
- Or you can learn the other ways.
- If not exported, functions are local
- Let's make a DrawLine function in drawing.js
- There is much more to modules, but this will do for now.