How to develop a component library as a standalone project, to live update with a Next.js project?

Viewed 36

I have 3 Next.js projects which all have copy/pasted versions of the same hooks, utils, and reusable UI components (buttons, tables, forms, etc.). Short version of the question is, how can I isolate these 3 folders into a separate repo/project and when I change the files in there, my 3 Next.js projects which have servers running will all get the latest changes on next refresh?

Basically, want to create a new repo/project which imports some Next.js stuff (like next/link), some other React stuff and uses JSX (well actually, TypeScript and .tsx), and has utils and hooks and some other odds and ends. These will be imported and used in the 3 web Next.js web apps I'm playing with. I don't know what the proper way of wiring these up though is. If I npm link my reusable repo/project (call it @foo/bar) into my websites, I don't think it will rebuild on each refresh. So I'm wondering what the general proper approach is to connecting the dots.

Can you show how you would wire things together, and what tools to potentially use? I am using ts-node and next and eslint and prettier and the rest is just details. To demonstrate the shared repo, you could just have an Button.tsx for all I need to know. You don't actually need to create a working project, but just a quick description on what to do.

Do I need to make some sort of file-watching thing from scratch, or is there a more standard approach?

This repo/project would basically all be frontend stuff for the intents and purposes of this question.

1 Answers

Sharing common code across different repositories usually requires the creation of a library. Creating node packages nowadays with private registries is not hard to accomplish.

But you also wanted the hot module reload to work across all these apps, which you are locally running. With a library, you would have to make use of special techniques in order to get this to work, which might be not much effort. This makes the following suggestion so unconventional.

I would very likely set up a self written NodeJS snippet using the build-in fs.watch(...), which will watch the code in one place and then update the same files in all other places in the moment they get changed.

This means your code is still multiple times implemented, but at least the hot reload is working and the manual work was minimized.

Related