Structuring a MEAN app so Express can find all the Jade files

I am building out a MEAN app right now that is getting big. I really need to start modularizing the app but right now my Express server is configured to look for Jade views in one folder

app.set('views', path.join(__dirname, '/app/views'));
app.set('view engine', 'jade');

The authors of these posts show the view files scattered about the app in the different module directories.

If I try to do this now, my Express server will not be able to see them. How can I make it so Express will be able to find all the Jade views?

Two solutions :

  • You can use a base folder named views and create subfolders inside views. For example, views/menu/, views/header/. To use this, you have to declare a basedir in Express so Jade will know where to look your views, by doing app.locals.basedir = __dirname + "/views";. Then, in your Jade file, use include /header/a.jade, include /menu/item1.jade etc...
  • Use Express App submounting feature. This allows you to modularize your main app into small apps, which all have their own routes, views etc... You can watch this nice video tutorial by TJ Holowaychuk to learn more about this.

Does that help you ?

I just start using module prefixes in my render calls and set my views base directory to be the parent directory of my modules. So if I started with:

app/views/page1.jade
app/views/page2.jade

and was doing res.render("page1"), I reorganize to:

app/module1/page1.jade
app/module2/page2.jade

and I do app.set("views", "app") then render with res.render("module1/page1").