React + backend - project structure when sharing code

前端 未结 3 1370
温柔的废话
温柔的废话 2021-02-03 13:59

I really like the folder structure as can be seen here when dealing with a React frontend and a some backend with express:

root
├── backend
|   ├── node_modules
         


        
3条回答
  •  广开言路
    2021-02-03 14:28

    I think it's perfectly reasonable to want to share code between your front and back end. It's one of the reasons we code in javascript instead of Ruby or PHP.

    You can accomplish exactly what you want by using yarn instead of npm and yarn workspaces: https://yarnpkg.com/lang/en/docs/workspaces/. At the top level you set up three modules/packages in your package.json (make sure you name the workspaces correctly in their respective package.json files):

    "workspaces": {
        "packages": [
            "backend",
            "frontend",
            "shared"
        ]
    },
    

    Once you do, you can import shared code in your CRA app or your back end simply like this:

    import { myFunction } from 'shared/src/myFile';
    

    The only drawback is that you can't import react components from the shared directory into frontend as long as you are using CRA. This won't affect you now since you only have one react app. Should you need to share react components among multiple projects, look into some on the suggestions above like bit.dev.

    This is not the only way, but it's among the simplest and most straight forward.

提交回复
热议问题