Often times I see the following directory structure and import pattern in Javascript projects:
ClassName/index.js pattern
RepoRoot
|-src
|-index.js
|-ClassName
|-index.js
|-SupportingClass.js
src/ClassName/index.js
import { SupportingClass } from './SupportingClass';
export class ClassName {
// Implementation
}
src/index.js
import { ClassName } from './ClassName';
This is all fine and dandy. It allows for a much cleaner import of the ClassName class. However I'm not a fan of the name of the class file index.js
not having the same name as the class's name. It:
- Makes it harder to locate the file in a file name search (Command+P in VS Code)
- You end up with just a very unhelpful
index.js
in the file tab in the IDE (yes I know some IDEs are smart enough to add a bit more context when you have more than one file of the same name open. That helps, but isn't a real solution imo) - Other files that aren't the indexes get much more descriptive names: SupportingClass.js, someUtils.js, etc.
ClassName/ClassName.js pattern
RepoRoot
|-src
|-index.js
|-ClassName
|-ClassName.js
|-SupportingClass.js
src/ClassName/ClassName.js
import { SupportingClass } from './SupportingClass';
export class ClassName {
// Implementation
}
src/index.js
import { ClassName } from './ClassName/ClassName';
This solves all of the problems I laid out, but makes the import of ClassName a bit duplicative. Probably not a big deal for most people especially with your IDE being able to auto import things for you nowadays.
However...
Just how webpack & node.js understand out of the box how to interpret the import path:
./ClassName
as./ClassName/index.js
Is there a setting or plugin that allows for it to interpret:
./ClassName
as./ClassName/ClassName.js
?
I've been wondering for years if such a thing existed but could never really find any literature on it. Curious if anyone here knows of anything.