Skip to content

organizing javascript sources

jackdarker edited this page Mar 2, 2021 · 1 revision

I have splitup my javascript-code in several files to make it easier to navigate. If you check the code you might wonder why this is working even if no import/export is used.
Thats because how the code is processed by the project-tools:
The compile process of the project will create a user.min.js file in project/scripts. The file-content will then be merged into the html-file. If you disable minify in src/config.json, you will see that user.min.js is mostly just all your js-files from src/scripts glued together. And this is done in alphabetic order of filenames and can cause issues!
Issues means you will get an immediate error-message because some function or variable of undefined could not be found. If you debug this you will see that several objects are not created or set to undefined.

Why is this so and what to do F.e. look at this, just 2 classes in 2 files.
file mySkills defines
class skCooking extends Effect {
.....
}

file Stat.js defines
class Effect {
.....
}

This will cause error because Stat.js is alphabetical sorted after mySkills.js . If you check user.min.js you will find that our class-definition got replaced with something like this: var skCooking = /*#__PURE__*/function (_Effect) {
_inherits(skCooking, _Effect);
var _super19 = _createSuper(skCooking);
.....
return skCooking;
}(Effect);

Because of the sorting in the file, this class-creation function will be executed before the class-creation of Effect and will thus fail.
If you rename Stat.js to aStat.js, then the code will work because the order of function calls is now correct ! Instead of renaming the file, you could also move the dependent file in subdirectory, because the compiler will process first all files in src/, then all files in the next subfolder a.s.o

Clone this wiki locally