Organizing frontend code of a single page app
Read time 1 min
Asset-based directory structure
Most Front-End projects I have seen use asset based directory structure: Styles are in one folder, scripts in another and so on.
/index.html /assets/ images/ awesomePlugin-sprite.png SearchBg.png SummaryBg.png scripts/ lib/ awesomePlugin.js jquery-1.8.0.js require.js model/ SearchModel.js SummaryModel.js view/ SearchView.js SummaryView.js styles/ main.scss search.scss summary.scss awesomePlugin.css templates/ SearchPanel.html Summary.html SummaryRow.html
This is probably a habit from times before single page apps existed and there were no modules for front end code. In Java world it’s like putting all exception classes under exception package and all controllers under controller package instead of having component based grouping.
Component-based directory structure
The idea is to put everything related to a component under same folder – images, templates, scripts and so on.
/index.html /app/ search/ SearchModel.js SearchView.js SearchPanel.html SearchBg.png search.scss summary/ SummaryView.js SummaryModel.js Summary.html SummaryRow.html SummaryBg.png summary.scss vendor/ jquery-1.8.0.js require.js awesomePlugin/ awesomePlugin.css awesomePlugin.js awesomePlugin-sprite.png
Benefits of component based directory structure
- When making changes to a component all the modifications take place in the same folder
- When using require.js (or similar) template imports can have relative paths instead of absolute
- Getting an overview of a component and searching related code is easy
- Deleting a component without leaving dead code behind is easy: Just delete the folder
- Structure of 3rd party components is consistent and they can be copied to project with their original structure
- Filtering by assets is still possible using file extension
- No need to repeat same folder name for different assets when grouping becomes necessary
- Re-organizing code is easier