There is no such thing as the “best” folder structure, but there are definitely ones that are better than the rest. This guide will talk about some of the better practices for creating your folders. Nevertheless, the most important thing about a good folder structure is consistency. You should stick with a folder structure and not deviate from it.

In the mern-boilerplate repository, all the folders are already created, and it’s highly unlikely that you’ll need to create new folders or modify existing ones.

Using index.ts files

Let’s say we have a folder like so:

main.ts
folderA/
	index.ts
  fileA.ts
// index.ts
export const B = 2
export const C = 3

// fileA.ts
export const A = 1

In main.ts, if I wanted to use A, B, and C, I’d have to import them from folderA/.

// main.ts
import { B, C } from './folderA'
import { A } from './folderA/fileA'

Wait a minute… why is B and C imported from ./folderA? Shouldn’t it be ./folderA/index?

Yes, it should be. But we don’t have to. This is because Node.js supports folders as modules, meaning when importing from a folder, it’ll automatically look for the index.ts file in the directory. This is extremely helpful when importing a lot of things from a folder.

Common uses

Typically, you wouldn’t have any code in index.ts files. The main purpose of the file is to export everything in the directory (i.e. a re-exporter). Lets take a look at this example:

main.ts
folderA/
	index.ts
	fileA.ts
	fileB.ts
	fileC.ts
// fileA.ts
export const A = 1

// fileB.ts
export const B = 2

// fileC.ts
export const C = 3

If we wanted to import all these variables from folderA/ into main.ts:

// main.ts
import { A } from './folderA/fileA'
import { B } from './folderA/fileB'
import { C } from './folderA/fileC'

You can clearly see how this would become really messy and long if we needed to import A LOT more from different files. This is where index.ts comes in.