Search code examples
javascriptreactjsecmascript-6modularityreact-scripts

Where should I store my React reusable components?


I have several ReactJS projects and I am starting to have a lot of reusable components. I do not want to publish them to npm or have them mixed with the imported node_modules directory at the root of my project. Where should they go?

My projects look like this:

  • project1/
    • node_modules/
    • src/
      • index.js
      • A.jsx
  • project2/
    • node_modules/
    • src/
      • index.js
      • A.jsx

A.jsx defines a reusable component and I'm just copying the file everywhere... I would like to have it in one place only and my projects use it with import A from 'A'.

I have tried to make symlinks to A.jsx in src/ or in node_modules/ but that won't compile, like react-scripts can't handle them. How have you worked around this? Thanks for your help!


Solution

  • I do not want them mixed with the imported node_modules

    Why not? Extracting your reusable components into their own library it's the best way to make them reusable. Once they are extracted, you can compose your projects by importing only what you need. You can also write their own tests without running the tests of an entire project. And finally you can handle different versions of the components independently of the projects.

    I have tried to make symlinks to A.jsx in src/ or in node_modules/ but…

    Symlinking files from one project to another one could be a good idea, but you are creating dependencies between your projects instead of creating dependencies between your projects and your components library. If you want to deploy project B that uses a component from project A, you will need to deploy both projects and recreate the symlink on the server. Also, project A is probably a bigger dependency (with its own dependencies) than a simple components library.

    I do not want to publish them to npm

    If you don't want to publish your components on NPM (I don't do neither), I'd still suggest you to extract your components into their own repository (GitLab has free private repositories).

    Then you can install the library directly from the repository like this:

    npm install git+ssh://[email protected]:Username/Repository-name
    

    It will create an entry in your package.json:

    "Repository-name": "git+ssh://[email protected]:Username/Repository-name"
    

    Then you can import your reusable components:

    import { ComponentA, ComponentB } from 'Repository-name'