i am learning react and writing my own components but i ran into an issue with project organisation.
here is my tree
Project_Folder - Components - Form - index.js - form.less - package.json - Button - index.js - button.less - package.json - node_modules - <million unknown packages> - application.js - webpack.conf.js
application.js i import form like that:
import Form from './Components/form/index.js'; Recently i figured if i just put my components folder in to
node_modules folder i can import my components with
import Form from 'Components/Form'; which is much better. but then developing this components becomes a hell just because whenever i go in to node folder it has millions of other modules which are required by webpack or babel or mini-CSS-extractor.
is there any solution to a better organization within node_modules, or maybe i should install dev tools globally ?
It is not a good idea to have your components inside the node_modules folder. Unless you are creating shareable code between teams through other tools/frameworks. Using your components there create a whole bunch of a problems that you have not faced YET :( !
i.e Node modules give the flexibility to share code using only the
package.json and ignoring them with
.gitignore. And reinstalling them through
Can you see the problem here?
To be able to share your components now inside the node_modules the options are:
Structuring folder is a delicate topic. It envolves a little bit of analysis of what suits your taste better and there is no right way of doing (even if you find experts that claim that such way is the correct)
For a better approach you could check the react documentation:
and a tutorial that I think will suffice in your case
Definitely you shouldn't keep your components in node_modules catalog, that's where you keep only dependencies of your app. Here's might be a good read for you. Especially when you'll be using git repository, you shouldn't copy your
node_modules catalog in there, because, as you've noticed - it's huuge. Let any other person working on this code to install dependecies on it's own, after cloning a repo.
There's few conventions - one will be to keep your components in
src/ catalog. My advise for you will be to install globally
create-react-app (a boilerplate generator for React sites, available here) and check it's conventions. Should be a great lesson for you.
One thing that concerns me is why there's
package.json inside each component? There should be only one
package.json file for a whole project. Read here.
If you want your file paths shorter and easier to read/use, you can create aliases with Webpack like this.