Escrito por Bruno Scherer,
3 minutos de leitura
File naming strategy for React Applications
A few alternatives to increase your development experience along the project
It is well known that React does not impose a style guide or design structure for your applications. In fact, this kind of freedom allows developers to use approaches that best suit their needs, and sometimes people struggle just not knowing “how to get started”. So here’s a tip from Dan Abramov.
Some time ago, I worked on a React project and I struggled at the beginning because I wanted to do things right from the start, so I wouldn’t have to worry about things like refactoring the project structure when it gets too expensive.
One of the biggest pains I had when developing react apps was when things started to look like this:
I know that keeping react code in an “index” file makes relative imports more elegant by referencing only the parent folder like this:
import Button from “../Button”
instead of:
import Button from “../Button/Button.js”
But IMHO the cost of that just doesn’t pay.
It was a waste of time to do things this way because every time I opened a new file to code, it also increased the cognitive load when I wanted to see a specific file that I had already opened before, and so I started looking for ways to get around this problem.
The simplest one…
… is to just ignore the fact that you’ll have to reference files in your imports when you don’t have an “index” file in the component folder, as long it is common to spend less time importing files when you are coding (and most of the time, these imports are done automatically…) than looking for a file in tabs, open editors, source control, etc.
You’ll end with something like this:
But if you really want your imports to reference only the component folder and still have your files with a more friendly name you can…
… Create an index file that exports a component
So when you
import Button from “../Button”
, node will look for an index file, and will find a component being exported.
You’ll get your imports behavior just like you used to with just index files, plus don’t get lost searching for a specific component looking for its path, at cost of having an extra file for each component.
Create a package.json
If Node does not found an index file, it will look for a package.json file and then look for “main” field.
I found this one very strange and I would never apply this in any project, but it is good to know that we have more than one way to import files without referring to files itself.
In the end…
… the choice is yours! Choose the approach that best suits your taste, because at the end of the day you will look at this structure very often.