Branch: master
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
88 lines (55 sloc) 2.27 KB
title description disqusPage
Reusable Modules
How to create pieces of code designed for reusability
Chapter 3: Reusable Modules


Let's say you want to create a chat thingie, and you want to decouple it, because you think that in the future you will definitely use it in some other project.

You need to treat it separately as a module:

Create a new folder /imports/modules/chat/

// file: /imports/modules/chat/client.js
// Do things related to client initialization (if necessary)

// file: /imports/modules/chat/server.js
// Do things related to server initialization, methods, listeners, etc (if necessary)

// file: /imports/modules/chat/db
// Apply the same principles

// file: /imports/modules/chat/api
// Apply the same principles

// file: /imports/modules/chat/client
// Store frontend stuff here.


Inside your re-usable module, never use absolute paths, only relative paths when importing:

import {Threads, Messages} from ../../db

Provide a README that specifies the module this uses, so it can be nicely reused.

// file: /imports/modules/chat/
// Store here the installation details and npm dependencies.
// Describe in general terms how to use this module

Event handling

Use an independent event handler. Not the global one.

// file: /imports/modules/chat/api/events.js

import EventEmitter from 'event-emitter';

const Events = {
    CHAT_NEW: ''

export default new EventEmitter();

If you want to unify emitters you can do so simply:

But if you want to do app specific logic when something in this module happens, I recommend you use the EventEmitter from chat module to listen for events.

A git submodule

Ofcourse now that you have it as a module, you can make it a git-submodule, and make it re-usable in multiple projects and maintainable.

Read more here:


The problem is that this app is not so independent, so you may find yourself conflicting with some npm dependencies, so keep that in mind. It depends on your whole structure and how you use it.

You can avoid this by properly versioning your git submodule.