Generate React-Router routes for your components automatically with MacroLock and Screen-Schemas
Tags: react, webdev, javascript, tutorial
Published: 2023-09-10 15:47:35

Hello, fellow developers! Today, I want to share with you two fantastic NPM modules that have been game-changers in my React projects. They’re called [MacroLock](https://www.npmjs.com/package/macrolock) and [Screen-Schemas](https://www.npmjs.com/package/screen-schemas), and they’ve made my development process smoother, faster, and more efficient.

![screenConfig example](https://miro.medium.com/v2/resize:fit:700/1*VoZ0ZIWrZqKfVSH6Lzhlvg.png)

## The Birth of MacroLock and Screen-Schemas

These two modules were born out of necessity while working on a project where I needed to automatically generate routes for the react router for all my screen components. After solving this problem, I thought it would be great to turn them into NPM modules so others could benefit too.

## What are MacroLock and Screen-Schemas?

[MacroLock](https://www.npmjs.com/package/macrolock) is a utility tool that helps you detect changes in a directory and execute a script if changes are detected. It does this by generating a checksum for the directory and comparing it with a previously stored checksum. If the checksums do not match, it means there have been changes in the directory, and [MacroLock](https://www.npmjs.com/package/macrolock) will execute the provided script.

[Screen-Schemas](https://www.npmjs.com/package/screen-schemas), on the other hand, is designed to generate screen descriptions from a directory of screen components for routes and navigation. It scans a directory for .tsx files, extracts configuration from comments in the files, and outputs a JSON file.

## How Do They Work Together?

In my project setup, I use these two modules in tandem with chokidar (a file watcher) to automate route generation based on my screen components. Here’s how it works:

1. Chokidar watches for any file changes in my screens directory.
2. When changes are detected, [MacroLock](https://www.npmjs.com/package/macrolock) checks if there have been any substantial changes (i.e., changes that affect the checksum).
3. However, MacroLock isn’t just a passive observer waiting for Chokidar to detect changes. It’s an active participant in the process, capable of running change detection whenever you like without dependence on an active watcher.
4. This means that even when there isn’t an active watcher, MacroLock can still detect changes made against a previously recorded checksum.
5. If there have been substantial changes, [Screen-Schemas](https://www.npmjs.com/package/screen-schemas) is triggered to scan all .tsx files in the screens directory.
6. [Screen-Schemas](https://www.npmjs.com/package/screen-schemas) then generates a routes.json file based on the configuration provided in the comments of each .tsx file.
7. This routes.json file is then used to dynamically generate routes in my React app.

**This setup ensures that no change goes unnoticed and your routes are always up-to-date, regardless of whether there’s an active watcher or not.**

Here’s a snippet from my package.json showing how I’ve set up these scripts:

```json
scripts: {  
"generate-routes": "yarn screen-schemas './src/components/screens/*.tsx' './src/routes.json'",  
"ifDif:buildroutes": "yarn macrolock ./src/components/screens ./locks/routes.lock 'yarn generate-routes'",  
"watch:routes": "chokidar './src/components/screens/' -c 'yarn ifDif:buildroutes'"  
}
```

And here’s how I use the generated routes.json in my React app:

```tsx
import routesJson from "../../routes.json";  
// Create a map with all components in the @self directory  
const components = import.meta.glob("/src/components/screens/*.tsx");  
export function RouterProvider() {  
 const { t } = useTranslation();  
 const routes = routesJson.map((route) => {  
 const Component = React.lazy(  
   () =>  
     components[  
     `/src/components/screens/${route.component}.tsx`  
       ]() as Promise<{  
         default: React.ComponentType<any>;  
       }>  
     );  
     // … rest of the code  
   });  
   // … rest of the code  
}  
...  
const router = createBrowserRouter([  
      ...routes.map((route) => {  
        return {  
          path: route.path,  
          element: (  
            <PageWrapper  
              routes={routes}  
              {...route}  
              hideBackButton={!Object.hasOwn(route, "onBackClick")}  
            >  
              {route.component}  
            </PageWrapper>  
          ),  
        };  
      }),  
    ]);  
<ReactRouterProvider router={router} />
```

## Integrating MacroLock in CI/CD Workflows

One of the powerful features of [MacroLock](https://www.npmjs.com/package/macrolock) is its ability to be integrated into your Continuous Integration and Continuous Deployment (CI/CD) workflows.

Thanks to the recorded lock file, [MacroLock](https://www.npmjs.com/package/macrolock) can be run as part of your CI/CD pipeline. This means that every time you push changes to your repository or deploy your application, [MacroLock](https://www.npmjs.com/package/macrolock) can automatically check for changes and execute necessary scripts if any changes are detected.

This feature ensures that your routes are always up-to-date and consistent with your screen components, even across different environments and deployment stages. It also eliminates the need for manual intervention in updating routes during the deployment process, making your deployments smoother and more reliable.

## Why Should You Use Them?

The beauty of this setup is that it automates a process that would otherwise be manual and prone to errors. It ensures that every time you add, remove, or modify a screen component, your routes are automatically updated to reflect these changes. This not only saves you time but also ensures consistency and accuracy in your routing.

Moreover, [MacroLock](https://www.npmjs.com/package/macrolock) isn’t limited to just working with [Screen-Schemas](https://www.npmjs.com/package/screen-schemas). You can use it to monitor any directory and execute any script when changes are detected. In my project, I also use it for generating barrel files and building Python scripts. This flexibility makes MacroLock a versatile tool that can be adapted for various use cases in your project.

## Wrapping Up

In conclusion, [MacroLock](https://www.npmjs.com/package/macrolock) and [Screen-Schemas](https://www.npmjs.com/package/screen-schemas) are powerful tools that can significantly enhance your React development process. They’re easy to install, simple to use, and highly customizable to suit your specific needs.

So why not give them a try? They might just become your new favorite tools in your developer toolkit!

## Contributing and Licensing

Both [MacroLock](https://www.npmjs.com/package/macrolock) and [Screen-Schemas](https://www.npmjs.com/package/screen-schemas) are open-source projects hosted on GitHub [MacroLock Repository](https://github.com/maxabrahamsson/macrolock), [Screen-Schemas Repository](https://github.com/maxabrahamsson/screen-schemas). Contributions in the form of issues, pull requests, or feedback are always welcome!

For licensing details, please refer to the respective repositories.

Happy coding!