nehalist
nehalist

Reputation: 1496

ES6 Module directory structure

I didn't find anything on Google but I'm wondering if there's a "best practise" of structuring an ES6 project in terms of directories and module exports.

Currently I do have two different ways in mind:

Using an index.js for every module and export everything:

app.js
modules/
  ModuleName/
    ModuleFile.js
    index.js

ModuleFile.js would look something like export class ModuleFile { }, the index.js would be simply

export * from 'ModuleFile'

This makes it possible to import files with import {ModuleFile} from 'modules/ModuleName'. Readable, but requires an index.js for every module, even if the module has just one single file.

Second approach would be without using index.js files, but that would mean import statements would become slightly redundant import {ModuleFile} from 'modules/ModuleName/ModuleFile'.

Are there any best practises on this topic?

Upvotes: 5

Views: 2073

Answers (1)

Enric A.
Enric A.

Reputation: 923

Your approach seems fine, I don't see a problem with it. In two different projects I've worked (different companies) it was the pattern used.

You could also put the ModuleFile.js content directly in index.js:

app.js
modules/
  ModuleName/
    index.js

Or create a file directly for a module:

app.js
modules/
    moduleName.js

In cases only a "file" is necessary. The evident problem is that changes or the growth of the module may force this structure to change. There would also be an inconsistence in terms of structure with other modules.

Upvotes: 1

Related Questions