Prism

Wednesday, March 3, 2021

Decluttering

 Currently, the chemistry lab game has a lot of clutter. Every file in the project is included on the index.html page, and it's not very modular. As the project gets larger, I will have to include more and more files all on the same page. This is not ideal.

While searching for a game library that I could use to simplify the process of creating this game, I came across requirejs. It appears to be similar to NodeJS's require function. With requirejs, I can take all the imports I have at the top of my index.html file, and convert them into one line. Then individual include each file that I need in the files that I need them in.

The first thing that I needed to do was add the following line of code to the index.html file.


	<script data-main="js/app" src="lib/require.js"></script>

The value of the data-main attribute is the location of the file that the scripts will start executing in.

Somewhere in the file you setup with data-main, you will need to call requirejs's config function. The config function is where you can setup your base URL, and aliases to paths in your project.


	// lib is the name of the directory where you will
    // keep files like jquery, and requirejs itself.
    // Paths are paths to directories that you would like to include 
    requirejs.config({
        baseUrl: 'lib',
        paths: {
            app: '../js/classes'
        }
    });

The key 'app' is an alias to the path ../js/classes in the code above, so you can replace app wherever you want to use the path "../js/classes" in requirejs code.

Then whenever you want to load a file you go like this:


	requirejs(["app/main"])

app/main is the path to the file you want to load.

If you want to define a module you go like this:


	define(["dependency1", "dependency2", "..."], function(dependency1, dependency2 ...) {
    	// module code 
        
        // return an object you can use when importing this module 
        return {}
        	
    })

The list of dependencies are other files with define in them.