callum
callum

Reputation: 37729

How to divide up a JavaScript codebase into modules?

The JavaScript in my web application has grown into one huge file. I want to break it up into modules so it's easier to manage.

I don't know if there are any established best practices for anatomizing the codebase of a web application, or if it just varies too much from project to project?

In particular:

Upvotes: 1

Views: 404

Answers (2)

All things being equal, you are better to create your modules around concepts specific to the app. This is more object oriented, and tends to group together code that is more likely to change together. This in turn makes your code easier to understand, more tolerant of change, easier to develop and extend (the benefits of "modularity").

Upvotes: 1

mbx-mbx
mbx-mbx

Reputation: 1775

If you take Separation of Concerns and Single Responsibility into account then each module/component etc. should be responsible for doing what it does and nothing else. Break down your modules by re factoring into small, easy to manage chunks that do it's job and nothing else.

In terms of your JS application you could take a look at some client side MVC frameworks (such as knockout, sproutcore, spine etc. to name but a few) these frameworks help to logically separate out views and layouts to controllers and models. You might also be interested in using something like require.js to load your modules as and when they are needed.

There is a very good book by Alex McCaw which is worth a read.

MVC is just one pattern, but it is a very popular pattern and addresses some of the concerns you have.

Best of luck.

Upvotes: 3

Related Questions