O'Reilly logo

Maintainable JavaScript by Nicholas C. Zakas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 13. File and Directory Structure

The first step before setting up a build system is to determine how your files and directories are laid out. This structure is heavily affected by the type of project. If the project is a standalone JavaScript library, you might want a different structure than you would want for a project containing all of the files for a website.

Best Practices

Regardless of the project type, there are several best practices that apply to JavaScript file and directory structure:

One object per file

Each JavaScript file should contain code for just one JavaScript object. This pattern is common to other programming languages and generally makes maintenance easier. Having multiple files with single objects reduces the risk of multiple people working on the same file at the same time. Even though today’s source control systems are incredibly good at merging changes from two different people, merge conflicts do still occur. The fewer files you have, the greater the likelihood of merge conflicts. Keeping one JavaScript object per file minimizes this risk.

Group related files in directories

If you have multiple objects that are related, put all of those files into a single directory. You might, for instance, have multiple files with code to make a single module. It makes sense to have a directory just for that module containing all of the files. Grouping related files helps developers locate functionality easily.

Keep third-party code separate

Any code that isn’t being ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required