0

I am working on an application using the MERN stack. The backend and frontend are in the same repository with this hierarchy:

my-project/
├── backend/
│   │
│   .
│   .   
│   └── package.json
├── frontend/
│   │
│   .
│   .   
│   └── package.json
├── shared/
│   ├── constants/
│   .
│   .   
│   ├── index.js
│   └── package.json
├── package.json
└── README.md

I want to have my constants shared between both the backend and frontend. I have the constants in the shared folder/module.

I also want to have any change in the shared package to be reflected in the other packages without needing to reinstall.

What is the best way for both the backend and frontend to use the shared package as a dependency?

  • Common or shared packages should be in root package.json. Node will find modules in upper directory if it is not available in local packages. It will move up one by one and at last it will look in global modules. – Abhishek Sharma Jun 09 '21 at 10:09

1 Answers1

0

You directory structure is almost ok to work with. But there might be some flaws,

my-project/
├── backend/
│   │
│   .
│   .   
│   └── package.json
├── frontend/
│   │
│   .
│   .   
│   └── package.json
├── shared/
│   ├── constants/
│   .
│   .   
│   ├── index.js
│   └── package.json // You might not need this
├── package.json // define shared packages here
└── README.md

For more details, how node

Abhishek Sharma
  • 2,485
  • 1
  • 21
  • 35
  • Interesting, how would the backend and frontend import the files from the shared package? – Zakaria Talhami Jun 09 '21 at 10:43
  • you just need to import them to your code. Node will traverse back in the directories and where ever it finds it, it will use from there. For example, in case of frontend, it will first look into `frontend/node_modules` folder, if not found, will move a step up and look in `my-project/node_modules` – Abhishek Sharma Jun 09 '21 at 11:10