Reputation: 397
I am at a point into developing an html5 game (sailing towards 500 lines in my main.js) where I'd need to split the code in several parts. I have already grouped different vars and functions by pertinence and moved these blocks into, for instance, main.js - game.js - player.js - enemy.js, ecc... and made them execute in the right order from html as to 'recompose' the main file I am working on now, like it was before splitting it:
<script src="main.js"></script>
<script src="game.js"></script>
<script src="player.js"></script>
<script src="enemy.js"></script>
It would work fine but this way all the variables are be accessible from the console. I tried to wrap each individual script into a self-executing function to prevent this (as is my main.js at the moment), but this approach would make variables I need to be globally accessible to fall out of scope. So what's the best practice in this case? I am reading around a lot but every solution i find seems to be behind my js skills or too abstract for such a small project like mine. Could someone point at the right direction?
Thank you.
Upvotes: 1
Views: 2281
Reputation: 205
It seems that you are struggling with the question: How should I modularize my app?
Instead of defining each dependency of your app in html:
<script src="main.js"></script>
<script src="game.js"></script>
<script src="player.js"></script>
<script src="enemy.js"></script>
It would be better to bundle your code with Webpack, Browserify, or some other module bundler. That way you wouldn't need to concern yourself on the ordering of <script>
tags.
You would then be able to include one <script>
tag in your html:
<script src="bundle.js"></script>
Where bundle.js
is the file containing your entire app code and any third party dependencies you may have used. Generating bundle.js
could be achieved by using a module bundler as mentioned above.
Depending on your chosen module bundler's support, you can opt in to use modules of types such as CommonJS, AMD, ES6, etc. By establishing modules
in your code, you will be able to export objects, functions, etc, and not pollute the global namespace. Thereby leading you to decouple your app from one giant file.
Upvotes: 2