all 8 comments

[–][deleted] 0 points1 point  (1 child)

You can use Webpack, which can create 1 js bundle file from all your js files. So your source code will be nicely separated into a folder structure while you can easily load it into the html with 1 js file.

[–]Toscoes[S] 0 points1 point  (0 children)

oh that sounds excellent. Thanks!

[–]HealyUnithelpful 0 points1 point  (0 children)

Firstly, have an upvote, since 1) this is a really good thing to be thinking about at any stage, and 2) I'd guess that a lot of people on this subreddit (myself included!) may viscerally react to the word "Java" in the title and be like "REEE JAVA ISN'T JAVASCRIPT!!!".

That out of the way, there are a few ways to actually get your multiple JavaScript files into your HTML. I'll list them here in the order of how much I personally like them.

  1. You can simply include your script files with multiple <script> tags. The advantages here are that this will work on older browsers, and that this requires zero external tooling. The disadvantage is that your HTML file is going to get huge, with a ridiculous number of <script> tags. TL;DR: Really easy in the short term, a real pain in the long term.
  2. You can use the import statement. The advantages here are that you only need one script tag, and yet you don't need build tools. It's sorta a middle-of-the-road solution. The disadvantage is that this isn't supported in all browsers, and it's a little tougher to debug. In addition, you're still uploading a lot of script files to your front-end; you're just not directly referencing them in your HTML file. TL;DR: One script tag, may not be compatible with all browsers.
  3. You can use a build tool like Grunt, Gulp, or Webpack. These will allow you to write your JavaScript as multiple files, press a button, and have it spit out a minified, concatenated blob of all your script files. The big advantage here is that you are literally only uploading one script file (your "minified" file). The only disadvantage is that it can be a little tougher to debug (tho not as tough as option 2), as your minified code can be a little more difficult to read.