In a JS project often you start of with a single file for a component, or anything for that matter.
At some stage you might find that you need additional files, for tests etc.
e.g.
I avoid that,
I feel it is much tidier to put all related files inside a folder and use the index file naming convention.
So, as soon as I need a second file I would generally move my-component.tsx into as
folder my-component/index.tsx
For CommonJS and esm modules, these two files are equivalent
A nice feature of this, is that the import: import { Foo } from "./my-service" will work with both my-service.ts and my-service/index.ts files, without requiring any changes to the import path
I find it a bit tiresome to do the dance of...
$ mkdir -p components/my-service
$ git mv components/my-component.tsx components/my-component/index.tsx
And if I mis-remember whether the file is not under version control yet, I might get a
fatal: not under version control, source=components/my-component.tsx, destination=components/my-component/index.tsx
-more annoyance..
Or perhaps more annoyingly, if I get it wrong the other way around and use mv, I could end up with a git status of
Changes not staged for commit: deleted: components/my-component.tsx Untracked files: components/my-component/
As the default mv command gets treated as a deletion and creation of a new file by git
I have written a bash script to automate the dance
$ ./nest.sh components/my-component.tsx
results in
$ tree components components └── my-component └── index.tsx
If the file is under version control, the script uses git mv otherwise uses plain old mv
multiple files...
$ ./nest.sh components/my-component.tsx $ ./nest.sh components/my-component.spec.ts $ ./nest.sh components/my-component.css
results in
$ tree components components └── my-component └── index.tsx └── index.spec.ts └── index.css
See the bash script in a Github Gist here
I have the script named as nest which is in a bin folder in my $PATH so I can use it as a command anywhere
The above is the detailed content of Streamlining File Organisation in JS Projects: Automating file Nesting with Bash. For more information, please follow other related articles on the PHP Chinese website!