Organizing files in Meteor
Starting hacking on a project with Meteor is lots of fun. But things can become a mess very easily. Meteor does not have too much restrictions on how to organize our project files but it’ll be useful to know some of its ways.
“packages” directory #
This is where all meteor
and atmosphere
packages are stored. And it’s a good place to store your own packages. If your projects contain any parts which does not change often and mostly independent from the rest of your project, you can create a package for that.
Another advantage of using packages is namespacing. Global variables you create inside packages are only available inside the package. Variables must be manually exported to other parts of your application using the package.json file.
If you’re writing packages, also try testing them using tinytest. It’s really easy to test with tinytest and it comes with Meteor by default.
“client” and “server” directories #
Files which goes under client
directory runs only on clients and files under server
runs only on the server. Which means, no need to wrap everything you write inside a giant if statement like this.
if (Meteor.isClient()) {
...
}
And the most important thing is that you can use client
and server
inside other directories. Let’s say you have several modules in your projects and each have their own client
or server
directory or both, you can arrange them like this (if you like to) or make up your own way to organize files using client
and server
directories.
/
+---blog/
| +---posts/
| | +---client/
| | | +---postsView.html
| | | +---postsView.less
| | | +---postsView.js
| | |
| | +---both
| | | +---validatePost.js
| | |
| | +---server/
| | +---collections.js
| | +---publications.js
| |
| +---gallery/
| +---client/
| +---imageGallery.html
| +---imageGallery.js
| +---imageGallery.less
|
+---user/
| +---client/
| +---server/
|
+---search/
+---server/
+---searchPostsMethod.js
In above example, the project contains 3 modules blog, user and search.
- Search module only has a Meteor method so it needs files to run only on server.
- User module can have both client side and server side code.
- Blog module has two sub modules posts and gallery.
- Gallery sub module only has client side code.
- Posts sub-module has both client and server side code.
- Posts sub-module also has a file common to both server and client.