When starting a new project one of the first things you are going to need to figure out is how you are going to organize your code.

What I like to do is group my modules by what they do under a single directory with a separate file for each module.

Consider a Backbone.js app. I may add a directory called resources for my models and collections and another directory called views for, well as the name implies.

Then under each directory I put an index.js file that imports and exports each module. Why do that? Because I would rather my api allow me to load all my models (or views or whatever else) from a single cohesive location all the while breaking those modules up into separate files.

For example, say we had 2 views under a views directory. For brevity I'll intentionally keep these small:

views/foo.js:

import Backbone from 'backbone';

const FooView = Backbone.View.extend({});

export default FooView;  

views/bar.js:

import Backbone from 'backbone';

const BarView = Backbone.View.extend({});

export default BarView;  

Ok so you could already import these like:

import FooView from './views/foo.js';  
import BarView from './views/bar.js';  

But by adding a views/index.js:

import FooView from './foo.js';  
import BarView from './bar.js';

export {  
  FooView,
  BarView
};

You can now import them as:

import {FooView, BarView} from './views';  

© 2017. All Rights Reserved.

Proudly published with Ghost